perm filename MANUAL.TEX[MF,DEK] blob sn#792552 filedate 1985-05-18 generic text, type C, neo UTF8
COMMENT ⊗   VALID 00026 PAGES
C REC  PAGE   DESCRIPTION
C00001 00001
C00004 00002	% This manual is copyright (C) 1984 by the American Mathematical Society.
C00006 00003	% halftitle
C00008 00004	% title
C00010 00005	% copyright
C00013 00006	% dedication
C00014 00007	% blank page
C00015 00008	% the preface
C00050 00009	% the table of contents
C00054 00010	\beginchapter Chapter 1. The Name of\\the Game
C00071 00011	\beginchapter Chapter 2. Coordinates
C00106 00012	\beginchapter Chapter 3. Curves
C00129 00013	\beginchapter Chapter 4. Pens
C00182 00014	\beginchapter Chapter 5. Running\\\MF
C00263 00015	\beginchapter Chapter 6. How \MF\\Reads What You\\Type
C00281 00016	\beginchapter Chapter 7. Variables
C00305 00017	\beginchapter Chapter 8. Algebraic\\Expressions
C00367 00018	\beginchapter Chapter 9. Equations
C00414 00019	\beginchapter Chapter 10. Assignments
C00427 00020	\beginchapter Chapter 11. Magnification
C00470 00021	\beginchapter Chapter 12. Boxes
C00510 00022	\beginchapter Chapter 13. Drawing, Filling,\\and Erasing
C00583 00023	\beginchapter Appendix A. Answers to\\All the\\Exercises
C00585 00024	\beginchapter Appendix J. Joining the\\\TeX\ Community
C00588 00025	\end  But Don, be sure to see MANMAC page 6 before you publish this!
C00589 00026	\beginchapter Chapter X. A Chapter\\Template
C00590 ENDMK
C⊗;
% This manual is copyright (C) 1984 by the American Mathematical Society.
% All rights are reserved!
% The file is distributed only for people to see its examples of TeX input,
% not for use in the preparation of books like The METAFONTbook.
% Permission for any other use of this file must be obtained in writing
% from the copyright holder and also from the publisher (Addison-Wesley).
\let\MFmanual=\!
%\loop\iftrue
%  \errmessage{This manual is copyrighted and should not be TeXed}\repeat
%\pausing1 \input manmac
%\ifproofmode\message{Proof mode is on!}\pausing1\fi
\input manmac[tex,dek]
% halftitle
\titlepage
\pageno=-1985
\line{\titlefont The {\manual ()*+,-.*}book}
\vfill
\ifproofmode
\rightline{The fine print in the upper right-hand}
\rightline{corner of each page is a draft of intended}
\rightline{index entries; it won't appear in the real book.}
\rightline{Some index entries will be in |typewriter type|}
\rightline{and/or enclosed in \<$\ldots$>, etc;}
\rightline{such typographic distinctions aren't shown here.}
\rightline{An index entry often extends for several pages;}
\rightline{the actual scope will be determined later.}
\rightline{Please note things that should be indexed but aren't.}
\fi
\eject
% title
\pageno=-1 % the front matter is numbered with roman numerals
\font\auth=amssmc10 scaled\magstep4 % used only on the title page
\font\elevenbf=ambx10 scaled\magstephalf % ditto
\font\elevenit=amti10 scaled\magstephalf % ditto
\font\elevenrm=amr10 scaled\magstephalf % ditto
\titlepage
\line{\titlefont The {\manual ()*+,-.*}book}
↑↑{Knuth, Donald Ervin}
↑↑{Bibby, Duane Robert}
\vskip 1pc
\baselineskip 13pt \elevenbf
\halign to\hsize{#\hfil\tabskip 0pt plus 1fil&#\hfil\tabskip0pt\cr
\kern1.5mm\auth DONALD \kern+2pt E. \kern+2pt KNUTH&
  \elevenit Stanford University\cr
\noalign{\vskip 12pc}
&\elevenit I\kern.7ptllustrations by\cr
&DUANE BIBBY\cr
\noalign{\vfill}
&\setbox0=\hbox{\man\char'44\char'44}%
\setbox2=\hbox to\wd0{\hss\man\char'43\hss}%
\raise2.3mm\box2\kern-\wd0\box0\cr % A-W logo
&ADDISON-\kern-1pt WESLEY\cr
&PUBLISHING COMP\kern-.13emANY\kern-1.5mm\cr
\noalign{\vskip.5pc \global\elevenrm}
&Reading, Massachusetts\cr
&Menlo Park, California\cr
&London\enspace$\cdot$\enspace Amsterdam\cr
&Don Mills, Ontario\enspace$\cdot$\enspace Sydney\cr}
\eject
% copyright
\titlepage
\eightpoint
\vbox to 8pc{}
\noindent\strut
The quotation on page xxx is copyright $\copyright$ 19xx by Xxxx,
and used by permission.
\medskip
\noindent
\TeX\ is a trademark of the American Mathematical Society.
\bigskip\medskip
\noindent
{\bf Library of Congress cataloging in publication data}
\medskip
{\tt\halign{#\hfil\cr
Knuth, Donald Ervin (1938-\cr
\ \ \  The METAFONTbook.\cr
\noalign{\medskip}
\ \ \  Includes index.\cr
\ \ \  1.~METAFONT (Computer system).\ \ 2.~Computerized\cr
typesetting.\ \ 3.~Typeface design.\ \ I.~Title.\cr
Z253.4.T47K58\ \ 1985\ \ \ \ \ \ \ \ \ 686.2\char13 xxxx\ \ \ \ \ \ 84-xxx\cr
ISBN 0-201-xxxxx-x\cr}}
\vfill
%\noindent
%{\sl \kern-1pt Second printing, Someday?}
%\smallskip
\noindent
Copyright $\copyright$ 1985 by the American Mathematical Society
\smallskip
\noindent
This book is published jointly by the American Mathematical Society
and Addison-\kern-1ptWesley Publishing Company.
All rights reserved. No part of this publication may be reproduced, stored in
a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without
the prior written permission of the publishers. Printed in the United
States of America. Published simultaneously in Canada.
\medskip
\noindent
ISBN 0-201-xxxxx-x\par
\noindent
ABCDEFGHIJ--HA--89876543
↑↑{Knuth, Donald Ervin}
\eject
% dedication
\titlepage
\vbox to 8pc{}
\rightline{\strut\eightssi To Hermann Zapf}
↑↑{Zapf, Hermann}
\vskip2pt
\rightline{\eightssi Whose strokes are the best}
\vfill
\eject
% blank page
\titlepage
\null\vfill
\eject
% the preface
\titlepage
\def\rhead{Preface}
\vbox to 8pc{
\rightline{\titlefont Preface}\vss}
{\topskip 9pc % this makes equal sinkage throughout the Preface
\vskip-\parskip
\tenpoint
\noindent\hang\hangafter-2
\hbox to 0pt{\hskip-\hangindent\man\char'176\hfill}\hskip-16pt
{\sc ENERATION} {\sc OF} {\sc LETTERFORMS} \strut by mathematical means
was first tried in the fifteenth century; it became popular in the
sixteenth and seventeenth centuries; and it was abandoned (for good
reasons) during the eighteenth century. Perhaps the twentieth century
will turn out to be the right time for this idea to make a comeback,
now that mathematics has advanced and computers are able to
do the calculations.

Modern printing equipment based on raster lines---in which metal ``type''
has been replaced by purely combinatorial patterns of zeroes and ones
that specify the desired position of ink in a discrete way---makes
mathematics and computer science increasingly relevant to printing.
We now have the ability to give a completely precise definition of letter
shapes that will produce essentially equivalent results on all raster-based
machines. Furthermore it is possible to include variable parameters in the
definitions of those shapes; computers can ``draw'' new fonts of characters
in seconds, so that a designer is now able to perform valuable experiments
that were previously unthinkable.

\MF\ is a system for the design of alphabets suited to raster-based
devices that print or display text. The characters that you are reading
were all designed with \MF\!, in a completely precise way; and they
were developed rather hastily by the author of the system, who is a rank
amateur at such things. It seems clear that further work with \MF\ has
the potential of producing typefaces of real ↑{beauty}, so this manual has
been written for people who would like to help advance the art of
mathematical type design.

A top-notch designer of typefaces needs to have an unusually good eye
and a highly developed sensitivity to the nuances of shapes.
A top-notch user of computer languages needs to have an unusual
talent for abstract reasoning and a highly-developed ability to
express intuitive ideas in formal terms. Very few people have both
of these unusual combinations of skills; hence the best products of
\MF\ will probably be collaborative efforts between two
people who complement each other's abilities. Indeed, this situation
isn't very different from the way types have been created for many
generations, except that the r\↑ole of ``punch-cutter'' is now being
played by skilled computer specialists instead of by skilled
metalworkers.

A \MF\ user writes a ``program'' for each letter or symbol that is
desired. These programs are different from ordinary computer programs,
because they are essentially {\sl declarative\/} rather than imperative.
In the \MF\ language you explain where the major components of a
desired shape are to be located, and how they relate to each other,
but you don't have to work out the details of exactly where the lines
cross, etc.; the computer takes over the work of solving equations as it
deduces the consequences of your specifications. One of the advantages of
\MF\ is that it provides a discipline according to which the principles
of a particular alphabet design can be stated precisely---the underlying
intelligence does not remain hidden in the mind of the designer, it is
spelled out in the programs. Thus it is comparatively easy to obtain
consistency where consistency is desirable, and to extend a font to
new symbols that are compatible with the existing ones.

It would be nice if a system like \MF\ were to simplify the task of
type design to the point where beautiful new alphabets could be
created in a few hours. This, alas, is impossible; an enormous
amount of subtlety lies behind the seemingly simple letter shapes that
we see every day, and the designers of high-quality typefaces have
done their work so well that we don't notice the underlying complexity.
One of the disadvantages of \MF\ is that a person can easily use it
to produce poor alphabets, cheaply and in great quantity. Let us hope
that such experiments will have educational value as they reveal why the
subtle tricks of the trade are important, but that they will not cause
bad workmanship to proliferate. Anybody can now produce a book in which
all of the type is home-made, but a person or team of persons should
expect to spend a year or more on the project if the type is actually
supposed to look right. \MF\ won't put today's type designers out of work;
on the contrary, it will tend to make them heroes and heroines, as more
and more people come to appreciate their skills.

Although there is no royal road to type design, there are some things that
can, in fact, be done well with \MF\ in an afternoon. Geometric designs
are rather easy; and it doesn't take long to make modifications to letters
or symbols that have previously been expressed in \MF\ form. Thus,
although comparatively few users of \MF\ will have the courage to do an
entire alphabet from scratch, there will be many who will enjoy
customizing someone else's design.

This book is not a text about mathematics or about computers. But if
you know the rudiments of those subjects (namely, contemporary high school
mathematics, together with the knowledge of how to use the text
editing or word processing facilities on your computing machine),
you should be able to use \MF\ with little difficulty after reading
what follows. Some parts of the exposition in the text are more obscure than others,
however, since the author has tried to satisfy experienced \MF\!ers
as well as beginners and casual users with a single manual. Therefore
a special symbol has been used to warn about esoterica: When you see the sign
$$\vbox{\hbox{\dbend}\vskip 11pt}$$
at the beginning of a paragraph, watch out for a ``↑{dangerous bend}''
in the train of thought---don't read such a paragraph unless you need to.
You will be able to use \MF\ reasonably well, even to design characters like
the dangerous-bend symbol itself, without reading the fine print in such
advanced sections.

Some of the paragraphs in this manual are so far out that they are rated
$$\vcenter{\hbox{\dbend\kern1pt\dbend}\vskip 11pt}\;;$$
everything that was said about single dangerous-bend signs goes double
for these. You should probably have at least a month's experience with
\MF\ before you attempt to fathom such doubly dangerous depths
of the system; in fact, most people will never need to know \MF\
in this much detail, even if they use it every day. After all, it's
possible to fry an egg without knowing anything about biochemistry.
Yet the whole story is here in case you're curious. \ (About \MF, not eggs.)

The reason for such different levels of complexity is that people change
as they grow accustomed to any powerful tool. When you first try to use
\MF\!, you'll find that some parts of it are very easy, while other things
will take some getting used to. At first you'll probably try to control
the shapes too rigidly, by overspecifying data that has been copied from
some other medium.  But later, after you have begun to get a feeling for
what the machine can do well, you'll be a different person, and you'll be
willing to let \MF\ help contribute to your designs as they are being
developed. As you gain more and more experience working with this unusual
apprentice, your perspective will continue to change and you will
run into different sorts of challenges.  That's the way it is with any
powerful tool: There's always more to learn, and there are always better
ways to do what you've done before.  At every stage in the development
you'll want a slightly different sort of manual.  You may even want to
write one yourself.  By paying attention to the dangerous bend signs in
this book you'll be better able to focus on the level that interests you
at a particular time.

Computer system manuals usually make dull reading, but take heart:
This one contains {\sc ↑{JOKES}} every once in a while. You might actually
enjoy reading it. \ (However, most of the jokes can only be appreciated
properly if you understand a technical point that is being made---so
read {\sl carefully}.)

Another noteworthy characteristic of this book is that it doesn't
always tell the ↑{truth}. When certain concepts of \MF\ are introduced
informally, general rules will be stated; afterwards you will find that the
rules aren't strictly true. In general, the later chapters contain more
reliable information than the earlier ones do. The author feels that this
technique of deliberate lying will actually make it easier for you to
learn the ideas. Once you understand a simple but false rule, it will not
be hard to supplement that rule with its exceptions.

In order to help you internalize what you're reading,
{\sc ↑{EXERCISES}} are sprinkled through this manual. It is generally intended
that every reader should try every exercise, except for questions that appear
in the ``dangerous bend'' areas. If you can't solve a problem, you
can always look up the answer.
But please, try first to solve it by yourself; then you'll learn more
and you'll learn faster. Furthermore, if you think you do know the solution,
you should turn to Appendix~A and check it out, just to make sure.

\bigskip
\hrule
\line{\vrule\hss\vbox{\medskip\ninepoint
\leftskip=\parindent \rightskip=\parindent
\noindent\strut W{\sc ARNING}: Type design can be hazardous to your other
interests.  Once you get hooked, you will develop intense feelings about
letterforms; the medium will intrude on the messages that you read. And you
will perpetually be thinking of improvements to the fonts that you see
everywhere, especially those of your own design.
\strut\medskip}\hss\vrule}
\hrule

\bigskip

The \MF\ language described here has very little in common with the
author's previous attempt at a language for alphabet design, because
five years of experience with the old system has made it clear that a
completely different approach is preferable. Both languages have
been called \MF; but henceforth the old language should be called
\MF\kern.05em79, and its use should rapidly fade away. Let's keep the name \MF\
for the language described here, since it is so much better, and since
it will never change again. ↑↑{MF79}

I wish to thank the hundreds of people who have helped me to formulate
this ``definitive edition'' of \MF\!, based on their experiences with
preliminary versions of the system.  In particular, John ↑{Hobby}
discovered many of the algorithms that have made the new language
possible. My work at Stanford has been generously supported by the
↑{National Science Foundation}, the ↑{Office of Naval Research}, the ↑{IBM
Corporation}, and the ↑{System Development Foundation}. I also wish to
thank the ↑{American Mathematical Society} for its encouragement and for
publishing the {\sl ↑{TUGboat}\/} newsletter (see Appendix~J).
Above all, I deeply thank my wife, Jill, for the inspiration, ↑↑{Knuth, Jill}
understanding, comfort, and support she has given me for more than
25~years, especially during the eight years that I have been
working intensively on mathematical typography.

\medskip
\line{{\sl Stanford, California}\hfil--- D. E. K.}↑↑{Knuth, Don}
\line{\sl June 1985\hfil}

} % end of the special \topskip
\endchapter

It is hoped that Divine Justice may find
some suitable affliction for the malefactors
who invent variations upon the alphabet of our fathers.~.\thinspace.\thinspace.
The type-founder, worthy mechanic, has asserted himself
with an overshadowing individuality,
defacing with his monstrous creations and revivals
every publication in the land.
\author AMBROSE ↑{BIERCE}, {\sl The Opinionator.~Alphab\↑etes\/} %
  (1911) % vol 10 of his collected works, p69
  % probably written originally in 1898 or 1899

\bigskip

Can the new process yield a result that, say,
a Club of Bibliophiles would recognise as a work of art
comparable to the choice books they have in their cabinets?
\author STANLEY ↑{MORISON}, {\sl Typographic Design in Relation to
	Photographic Composition\/} (1958) % pp 4--5

\eject
% the table of contents
\titlepage
\vbox to 8pc{
\rightline{\titlefont Contents}
\vfill}
↑↑{Contents of this manual, table}
\def\rhead{Contents}
\tenpoint
\begingroup
\countdef\counter=255
\def\diamondleaders{\global\advance\counter by 1
  \ifodd\counter \kern-10pt \fi
  \leaders\hbox to 20pt{\ifodd\counter \kern13pt \else\kern3pt \fi
    .\hss}}
\baselineskip 15pt plus 5pt
\def\\#1. #2. #3.{\line{\strut
    \hbox to\parindent{\bf\hbox to 1em{\hss#1}\hss}%
    \rm#2\diamondleaders\hfil\hbox to 2em{\hss#3}}}
\\1. The Name of the Game. 1.
\\2. Coordinates. 5.
\\3. Curves. 13.
\\4. Pens. 21.
\\5. Running \MF. 33.
\\6. How \MF\ Reads What You Type. 51.
\\7. Variables. 55.
\\8. Algebraic Expressions. 61.
\\9. Equations. 77.
\\10. Assignments. 89.
\\11. Magnification. 93.
\\12. Boxes. 103.
\\13. Drawing, Filling, and Erasing. 111.
\\14. Paths. 125.
\\15. Transformations. xxx.
\\16. Calligraphic Effects. xxx.
\\17. Grouping. xxx.
\\18. Definitions (also called Macros). xxx.
\\19. Conditions and Loops. xxx.
\\20. More about Macros. xxx.
\\21. Random Numbers. xxx.
\\22. Strings. xxx.
\\23. Online Displays. xxx.
\eject
\vbox to 8pc{}
\\24. Discreteness and Discretion. xxx.
\\25. Summary of Expressions. xxx.
\\26. Summary of the Language. xxx.
\\27. Recovering from Errors. xxx.
\null
\leftline{\indent\bf Appendices}
\\A. Answers to All the Exercises. 125.
\\B. Basic Operations. xxx.
\\C. Character Codes. xxx.
\\D. Dirty Tricks. xxx.
\\E. Examples. xxx.
\\F. Font Metric Information. xxx.
\\G. Generic Font Files. xxx.
\\H. Hardcopy Proofs. xxx.
\\I\hskip 1pt. Index. xxx.
\\J. Joining the \TeX\ Community. 139.
\null % 17 lines so far to balance the 23 on the other page
\null % 18
\null % 19
\null % 20
\null % 21
\null % 22
\null % 23
\eject
\endgroup
\beginchapter Chapter 1. The Name of\\the Game

\pageno=1 % This is page number 1, number 1,
This is a book about a computer system called \MF\!, just as {\sl The \TeX
book\/} is about \TeX.  \MF\ and \TeX\ are good friends who intend to live
together for a long time.  Between them they take care of the two most
fundamental tasks of typesetting:  \TeX\ puts characters into the proper
positions on a page, while \MF\ determines the shapes of the characters
themselves. ↑↑{TeX} ↑↑{METAFONT, the name}

Why is the system called \MF\thinspace? The `-{\manual FONT}\thinspace'
part is easy to understand, because sets of related characters that are
used in typesetting are traditionally known as fonts of type. The
`{\manual META}-' part is more interesting: It indicates that we are
interested in making high-level descriptions that transcend any of the
individual fonts being described.

Newly coined words beginning with `meta-' generally reflect our contemporary
inclination to view things from outside or above, at a more abstract level than
before, with what we feel is a more mature understanding. We now have
metapsychology (the study of how the mind relates to its containing body),
metahistory (the study of principles that control the course of events),
metamathematics (the study of mathematical reasoning), metafiction
(literary works that explicitly acknowledge their own forms), and so on.
A metamathematician proves metatheorems (theorems about theorems);
a computer scientist often works with metalanguages (languages for
describing languages). Similarly, a ↑{meta-font} is a schematic description
of the shapes in a family of related fonts; the letterforms change
appropriately as their underlying parameters change.

Meta-design is much more difficult than design; it's easier to draw something
than to explain how to draw it. One of the problems is that it's hard to
envision many different sets of potential specifications all at once.
Another is that a computer has to be told absolutely everything.
However, once we have successfully explained how to draw something
in a sufficiently general manner, the same explanation will work for
related shapes, in different circumstances; so~the time spent in formulating
a precise explanation turns out to be worth it.

Typefaces intended for text are normally seen small, and our eyes can read
them best when the letters have been designed specifically for the size at
which they are actually used. Although it is tempting to get 7-point fonts
by simply making a 70\% reduction from the 10-point size, this shortcut
leads to a serious degradation of quality. Much better results can be
obtained by incorporating parametric variations into a meta-design.  In
fact, there are advantages to built-in variability even when you want to
produce only one font of type in a single size, because it allows you to
postpone making decisions about many aspects of your design. If you leave
certain things undefined, treating them as parameters instead of
``freezing'' the specifications at an early stage, the computer will be
able to draw lots of examples with different settings of the parameters,
and you will be able to see the results of all those experiments at the final
size. This will greatly increase your ability to edit and fine-tune the font.

If meta-fonts are so much better than plain old ordinary fonts, why weren't
they developed long ago? The main reason is that computers did not exist until
recently. People find it difficult and dull to carry out calculations with
a multiplicity of parameters, while today's machines do such tasks with ease.
The introduction of parameters is a natural outgrowth of automation.

OK, let's grant that meta-fonts sound good, at least in theory. There's still
the practical problem about how to achieve them. How can we actually
specify shapes that depend on unspecified parameters?

If only one parameter is varying, it's fairly easy to solve the problem in
a visual way, by overlaying a series of drawings that show graphically how
the shape changes. For example, if the parameter varies from 0 to~1, we
might prepare five sketches, corresponding to the parameter values 0,
$1\over4$, $1\over2$, $3\over4$, and~1. If these sketches follow a
consistent pattern, we can readily interpolate to find the shape for a
value like~$2\over3$ that lies between two of the given ones. We might
even try extrapolating to parameter values like 1$1\over4$.

But if there are two or more independent parameters, a purely visual solution
becomes too cumbersome. We must go to a verbal approach, using some sort
of language to describe the desired drawings. Let's imagine, for example,
that we want to explain the shape of a certain letter `a' to a friend in
a distant country, using only a telephone for communication; our friend
is supposed to be able to reconstruct exactly the shape we have in mind.
Once we figure out a sufficiently natural way to do that, for a particular
fixed shape, it isn't much of a trick to go further and make our verbal
description more general, by including variable parameters instead of
restricting ourselves to constants.

An analogy to cooking might make this point clearer. Suppose you have just
baked a delicious berry pie, and your friends ask you to tell them the
↑{recipe} so that they can bake one too. If you have developed your cooking
skills entirely by intuition, you might find it difficult to record exactly
what you did. But there is a traditional language of recipes in which you
could communicate the steps you followed; and if you take careful measurements,
you might find that you used, say, 1$1\over4$ cups of sugar. The next step,
if you were instructing a computer-controlled cooking machine, would be to
go to a meta-recipe in which you use, say, $.25x$ cups of sugar for $x$
cups of berries; or $.3x+.2y$ cups for $x$~cups of boysenberries and
$y$~cups of blackberries.

In other words, going from design to meta-design is essentially like
going from arithmetic to elementary algebra. Numbers are replaced
by simple formulas that involve unknown quantities. We will see
many examples of this.

A \MF\ definition of a complete typeface generally consists of three
main parts. First there is a rather mundane set of subroutines that take care
of necessary administrative details, such as assigning code numbers
to individual characters; each character must also
be positioned properly inside an invisible ``box,'' so that typesetting
systems will produce the correct spacing. Next comes a more interesting
collection of subroutines, designed to draw the basic strokes characteristic
of the typeface (e.g., the serifs, bowls, arms, arches, and so on).
These subroutines will typically be described in terms of their own special
parameters, so that they can produce a variety of related strokes;
a serif subroutine will, for example, be able to draw serifs of
different lengths, although all of the serifs it draws should
have the same ``feeling.'' Finally, there are routines for each of
the characters. If the subroutines in the first and second parts have been
chosen well, the routines of the third part will be fairly high-level descriptions
that don't concern themselves unnecessarily with details; for example, it
may be possible to substitute a different serif-drawing subroutine without
changing any of the programs that use that subroutine, thereby obtaining
a typeface of quite a different flavor. [A particularly striking example
of this approach has been worked out by John~D. ↑{Hobby} and ↑{Gu} Guoan
in ``A Chinese Meta-Font,'' {\sl TUGboat\/ \bf5} (1984), 119--136. By
changing a set of 13 basic stroke subroutines, they were able to draw 128
sample ↑{Chinese characters} in three different styles (Song, Long Song,
and Bold), using the same programs for the characters.]

A well-written \MF\ program will express the designer's intentions more
clearly than mere drawings ever can, because the language of algebra has
simple ``idioms'' that make it possible to elucidate many visual relationships.
Thus, \MF\ programs can be used to communicate knowledge
about type design, just as recipes convey the expertise of a chef. But
algebraic formulas are not easy to understand in isolation; \MF\ descriptions
are meant to be read with an accompanying illustration, just as the
constructions in geometry textbooks are accompanied by diagrams.
Nobody is ever expected to read the text of a \MF\ program and say,
``Ah, what a beautiful letter!'' But with one or more enlarged pictures
of the letter, based on one or more settings of the parameters, a reader
of the \MF\ program should be able to say, ``Ah, I~understand how this
beautiful letter was drawn!'' We shall see that the \MF\ system makes it
fairly easy to obtain annotated proof drawings that you can hold in your
hand as you are working with a program.

Although \MF\ is intended to provide a relatively painless way to describe
meta-fonts, you can of course use it also to describe unvarying shapes that
have no ``meta-ness'' at all. Indeed, you need not even use it to produce
fonts; the system will happily draw geometric designs that have no relation
to the characters or glyphs of any alphabet or script. The author
occasionally uses \MF\ simply as a pocket calculator, to do elementary
arithmetic in an interactive way. A computer doesn't mind if its
programs are put to purposes that don't match their names.

\endchapter

[Tinguely] made some large, brightly coloured open reliefs,
juxtaposing stationary and mobile shapes.
He later gave them names like\/ %
{\rm Meta-↑{Kandinsky}}\kern-1pt\ and\/ {\rm Meta-↑{Herbin}}\kern-.5pt,
to clarify the ideas and attitudes %
that lay at the root of their conception.
\author K. G. PONTUS ↑{HULT\'EN}, {\sl Jean ↑{Tinguely}: M\'eta\/} (1972)
 % translated from German by Mary Whittall, 1975, p46

\bigskip

The idea of a meta-font should now be clear. But what good is it?
The ability to manipulate lots of parameters may be interesting and fun,
but does anybody really need a 6\/{\manual\seventh}-point font
that is one fourth of the way between Baskerville and Helvetica?
\author DONALD E. ↑{KNUTH}, {\sl The Concept of a Meta-Font\/} (1982)
 % Visible Language 16, p19

\eject
\beginchapter Chapter 2. Coordinates

If we want to tell a computer how to draw a particular shape, we need a way to
explain where the key points of that shape are supposed to be.
\MF\ uses standard {\sl ↑{Cartesian} ↑{coordinates}\/} for this purpose:
The location of a point is defined by specifying its $x$~coordinate, which
is the number of units to the right of some reference point, and its
$y$~coordinate, which is the number of units upwards from the reference
point. First we determine the horizontal (left/right) component of a
point's position, then we determine the vertical (up/down) component.
\MF's world is two-dimensional, so two coordinates are enough.%
↑↑{x coordinate} ↑↑{y coordinate}

For example, let's consider the following six points:
\displayfig 2a (4.75pc)
\MF's names for the positions of these points are
\begindisplay
$(x↓1,y↓1)=(0,100)$;&$(x↓2,y↓2)=(100,100)$;&$(x↓3,y↓3)=(200,100)$;\cr
$(x↓4,y↓4)=(0,\hfill0)$;&$(x↓5,y↓5)=(100,\hfill0)$;&
  $(x↓6,y↓6)=(200,\hfill0)$.\cr
\enddisplay
Point 4 is the same as the reference point, since both of its coordinates
are zero; to get to point~$3=(200,100)$, you start at the reference point
and go 200~steps right and 100~up; and so on.

\exercise Which of the six example points is closest to the point $(60,30)$?
\answer Point $5=(100,0)$ is closer than any of the others. \ (See
the diagram below.)

\exercise True or false: All points that lie on a given horizontal straight
line have the same $x$~coordinate.
\answer \decreasehsize 15pc
\rightfig A2a (13pc x 5pc) ↑9pt
False. But they all do have the same $y$~coordinate.

\exercise Explain where the point $(-5,15)$ is located.
\answer 5 units to the {\sl left\/} of the reference point, and 15 units up.

\exercise What are the coordinates of a point that lies exactly
60~units below point~6 in the diagram above?
(``Below'' means ``down the page,'' not ``under the page.'')
\answer \restorehsize $(200,-60)$.

In a typical application of \MF\!, you prepare a rough sketch of the shape
you plan to define, on a piece of ↑{graph paper}, and you label important
points on that sketch with any convenient numbers. Then you write a \MF\
program that explains (i)~the coordinates of those key points, and
(ii)~the lines or curves that are supposed to go between them.

\MF\ has its own internal graph paper, which forms a so-called ↑{raster}
or ↑{grid} consisting of square ``↑{pixels}.'' ↑↑{pel, see pixel}
The output of \MF\ will \hbox{specify} that certain of the pixels are ``black''
and that the others are ``white''; thus, the computer essentially converts
shapes into binary patterns like the designs a~person can make when doing
needlepoint with two colors of yarn.

Coordinates are lengths, but we haven't discussed yet what the units of
length actually are. It's important to choose convenient units,
and \MF's coordinates are given in units of pixels.  The little squares
illustrated on the previous page, which correspond to differences
of 10~units in an $x$~coordinate or a $y$~coordinate, therefore represent
$10\times10$ arrays of pixels, and the rectangle enclosed by our six
example points contains 20,000 pixels altogether.\footnote*{We
sometimes use the term ``pixel'' to mean a square picture element,
but sometimes we use it to signify a one-dimensional unit of length.
A square pixel is one pixel-unit wide and one pixel-unit tall.}

Coordinates don't have to be whole numbers. You can refer, for example,
to point $(31.5,42.5)$, which lies smack in the middle of the pixel
whose corners are at $(31,42)$, $(31,43)$, $(32,42)$, and~$(32,43)$.
The computer works internally with coordinates that are integer multiples
of ${1\over65536}\approx0.00002$ of the width of a pixel, so it is
capable of making very fine distinctions. But \MF\ will never make
a pixel half black; it's all or nothing, as far as the output is concerned.

The fineness of a grid is usually called its {\sl ↑{resolution}}, and
resolution is usually expressed in pixel units per inch (in America)
or pixel units per millimeter (elsewhere). For example, the type you
are now reading was prepared by \MF\ with a resolution of slightly
more than 700 pixels to the inch, but with slightly fewer than 30 pixels
per~mm. For the time being we shall assume that the pixels are so tiny
that the operation of rounding to whole pixels is unimportant;
later we will consider the important questions that arise when \MF\ is
producing low-resolution output.

It's usually desirable to write \MF\ programs that can manufacture fonts
at many different resolutions, so that a variety of low-resolution printing
devices will be able to make proofs that are compatible with a variety of
high-resolution devices. Therefore the key points in \MF\ programs are rarely
specified in terms of pure numbers like `100'\thinspace; we generally make
the coordinates relative to some other resolution-dependent quantity, so
that changes will be easy to make. For example, it would have been better
to use a definition something like the following, for the six points
considered earlier:
\begindisplay
$(x↓1,y↓1)=(0,b)$;&$(x↓2,y↓2)=(a,b)$;&$(x↓3,y↓3)=(2a,b)$;\cr
$(x↓4,y↓4)=(0,0)$;&$(x↓5,y↓5)=(a,0)$;&$(x↓6,y↓6)=(2a,0)$;\cr
\enddisplay
then the quantities $a$ and $b$ can be defined in some way appropriate to
the desired resolution. We had $a=b=100$ in our previous example, but
such constant values leave us with little or no flexibility.

Notice the quantity `$2a$' in the definitions of $x↓3$ and $x↓6$; \MF\
understands enough algebra to know that this means twice the value of~$a$,
whatever $a$~is. We observed in Chapter~1 that simple uses of algebra give
\MF\ its meta-ness.  Indeed, it is interesting to note from a historical
standpoint that ↑{Cartesian} coordinates are named after Ren\'e
↑{Descartes}, not because he invented the idea of coordinates, but because
he showed how to get much more out of that idea by applying algebraic
methods. People had long since been using coordinates for such things as
latitudes and longitudes, but Descartes observed that by putting unknown
quantities into the coordinates it became possible to describe infinite
sets of related points, and to deduce properties of curves that were
extremely difficult to work out using geometrical methods alone.

So far we have specified some points, but we haven't actually done
anything with them.  Let's suppose that we want to draw a straight line
from point~1 to point~6, obtaining
\displayfig 2b (5pc)
One way to do this with \MF\ is to say
\begindisplay
@draw@  $(x↓1,y↓1)\to(x↓6,y↓6)$.
\enddisplay
The `$\to$' ↑↑{..} here tells the computer to connect two points.

It turns out that we often want to write formulas like `$(x↓1,y↓1)$', so
it will be possible to save lots of time if we have a special abbreviation
for such things. Henceforth we shall use the notation $z↓1$ to stand for
$(x↓1,y↓1)$, and in general ↑↑{z convention}
$z↓k$ with an arbitrary subscript will stand for the point $(x↓k,y↓k)$.
The `@draw@' command above can therefore be written more simply as
\begindisplay
↑@draw@ $z↓1\to z↓6$.
\enddisplay
Adding two more straight lines by saying, `@draw@ $z↓2\to z↓5$' and
`@draw@ $z↓3\to z↓4$', we obtain a design that is slightly reminiscent of
the ↑{Union Jack}:
\displayfig 2c (5.5pc)
We shall call this a ↑{hex symbol}, because it has six endpoints. Notice
that the straight lines here have some thickness, and they are rounded at
the ends as if they had been drawn with a felt-tip pen having a circular
nib.  \MF\ provides many ways to control the thicknesses of lines and to
vary the terminal shapes, but we shall discuss such things in later
chapters because our main concern right now is to learn about coordinates.

If the hex symbol is scaled down so that its height parameter $b$
is exactly equal to the height of the letters in this paragraph,
it looks like this: `\thinspace{\manual\hexa}\thinspace'. Just for fun,
let's try to typeset ten of them in a row:
\begindisplay
{\manual\hexa\hexa\hexa\hexa\hexa\hexa\hexa\hexa\hexa\hexa}
\enddisplay
How easy it is to do this!\footnote*{Now that authors have
for the first time the power to invent new symbols with great ease, and to
have those characters printed in their manuscripts on a wide variety of
typesetting devices, we must face the question of how much experimentation
is desirable. Will font freaks abuse this toy by overdoing it? Is it wise
to introduce new symbols by the thousands? Such questions are beyond
the scope of this book; but it is easy to imagine an epidemic of
fontomania occurring, once people realize how much fun it is to design
their own characters, hence it may be necessary to perform fontal
lobotomies.} % This joke due to Richard Palais, commenting on draft in 1979

Let's look a bit more closely at this new character.
The {\manual\hexa} is a bit too tall, because it extends above points
1, 2, and~3 when the thickness of the lines is taken into account;
similarly, it sinks a bit too much below the baseline (i.e., below
the line $y=0$ that contains points 4, 5, and~6). In order to correct
this, we want to move the key points slightly. For example, point~$z↓1$
should not be exactly at $(0,b)$, but let's arrange things so that
the top of the pen is at $(0,b)$ when the center of the pen is at~$z↓1$.
We can express this condition for the top three points as follows:
\begindisplay
$"top"\,z↓1=(0,b)$;&$"top"\,z↓2=(a,b)$;&$"top"\,z↓3=(2a,b)$;\cr
\noalign{\vskip\belowdisplayskip
\leftline{similarly, the remedy for points 4, 5, and 6 is to specify
 the equations}
\vskip\abovedisplayskip}
$"bot"\,z↓4=(0,0)$;&$"bot"\,z↓5=(a,0)$;&$"bot"\,z↓6=(2a,0)$.\cr
\enddisplay
The resulting squashed-in character is
\displayfig 2d (4.5pc)
(shown here with the original weight `\thinspace{\manual\hexb}\thinspace'
and also in a bolder version `\thinspace{\manual\hexc}\thinspace').

\exercise Ten of these bold hexes produce `\thinspace{\manual
\hexc\hexc\hexc\hexc\hexc\hexc\hexc\hexc\hexc\hexc}\thinspace'; notice that
adjacent symbols overlap each other. The reason is that each character
has width $2a$, hence point~3 of one character coincides with point~1
of the next. Suppose that we actually want the characters to be
completely confined to a rectangular box of width~$2a$, so that
adjacent characters come just shy of touching (\thinspace{\manual
\hexd\hexd\hexd\hexd\hexd\hexd\hexd\hexd\hexd\hexd}\thinspace).
Try to guess how the point-defining equations above could be modified
to make this happen, assuming that
\MF\ has operations `"lft"' and `"rt"' analogous to `"top"' and `"bot"'.
\answer $"top"\,"lft"\,z↓1=(0,b)$; \ $"top"\,z↓2=(a,b)$; \
$"top"\,"rt"\,z↓3=(2a-1,b)$; \ $"bot"\,"lft"\,z↓4=(0,0)$; \
$"bot"\,z↓5=(a,0)$; \ $"bot"\,"rt"\,z↓6=(2a-1,0)$.
Adjacent characters will be separated by exactly one column of white
pixels, if character is $2a$ pixels wide, because the right edge of
black pixels is specified here to have the $x$~coordinate $2a-1$.

Pairs of coordinates can be thought of as ``↑{vectors}'' or ``displacements''
as well as points. For example, $(15,8)$ can be regarded as a command to
go right~15 and up~8; then point $(15,8)$ is the position we get to after
starting at the reference point and obeying the command $(15,8)$. This
interpretation works out nicely when we consider addition of vectors:
If we move according to the vector $(15,8)$ and then move according to
$(7,-3)$, the result is the same as if we move $(15,8)+(7,-3)=
(15+7,8-3)=(22,5)$. The sum of two vectors $z↓1=(x↓1,y↓1)$ and $z↓2=
(x↓2,y↓2)$ is the vector $z↓1+z↓2=(x↓1+x↓2,y↓1+y↓2)$ obtained by adding
$x$ and $y$ components separately. This vector represents the result of
moving by vector $z↓1$ and then moving by vector $z↓2$; alternatively,
$z↓1+z↓2$ represents the point you get~to by starting at point~$z↓1$
↑↑{addition of vectors}
and moving by vector~$z↓2$.

\exercise Consider the four fundamental vectors $(0,1)$, $(1,0)$,
$(0,-1)$, and $(-1,0)$. Which of them corresponds to moving one pixel unit
(a)~to the right? (b)~to the left? (c)~down? (d)~up? 
\answer $"right"=(1,0)$; $"left"=(-1,0)$; $"down"=(0,-1)$; $"up"=(0,1)$.

Vectors can be subtracted as well as added; the value of $z↓1-z↓2$ is simply
$(x↓1-x↓2,y↓1-y↓2)$. Furthermore it is natural to multiply a vector
by a single number~$c$: The quantity $c$~times $(x,y)$, which is written $c(x,y)$,
equals $(cx,cy)$. Thus, for example, $2z=2(x,y)=(2x,2y)$ turns out
to be equal to $z+z$. ↑↑{multiplication of vector by scalar}
In the special case $c=-1$ we write $-(x,y)=(-x,-y)$. ↑↑{negation of vectors}

Now we come to an important notion, based on the fact that subtraction
is the opposite of addition. {\sl If $z↓1$ and $z↓2$ are any two points,
then $z↓2-z↓1$ is the vector that corresponds to moving from $z↓1$ to~$z↓2$.}
The reason is simply that $z↓2-z↓1$ is what we must add to~$z↓1$ in order
to get~$z↓2$: i.e., $z↓1+(z↓2-z↓1)=z↓2$. We shall call this the
{\sl ↑{vector subtraction principle}}. ↑↑{subtraction of vectors}
It is used frequently in \MF\ programs when the designer wants to specify the
direction and/or distance of one point from another.

\MF\ programs often use another idea to express relations between points.
Suppose we start at point~$z↓1$ and travel in a straight line from there
in the direction of point~$z↓2$, but we don't go all the way. There's a
special notation for this, using square brackets: ↑↑{bracket notation}
\begindisplay \advance\baselineskip by 3pt
${1\over3}[z↓1,z↓2]$ is the point one-third of the way from $z↓1$ to $z↓2$,\cr
${1\over2}[z↓1,z↓2]$ is the point midway between $z↓1$ and $z↓2$,\cr
$.8[z↓1,z↓2]$ is the point eight-tenths of the way from $z↓1$ to $z↓2$,\cr
\enddisplay
and, in general, $t[z↓1,z↓2]$ stands for the point that lies a fraction
$t$ of the way from $z↓1$ to~$z↓2$. We call this the operation of {\sl
↑{mediation}\/} between points, or (informally) the ``↑{of-the-way
function}.'' If the fraction~$t$ increases from 0 to~1, the expression
$t[z↓1,z↓2]$ traces out a straight line from $z↓1$ to~$z↓2$. According to
the vector subtraction principle, we must move $z↓2-z↓1$ in order to go all
the way from $z↓1$ to~$z↓2$, hence the point $t$~of~the~way between them is
\begindisplay
$t[z↓1,z↓2]\;=\;z↓1+t(z↓2-z↓1)$.
\enddisplay
This is a general formula by which we can calculate $t[z↓1,z↓2]$ for any
given values of $t$, $z↓1$, and~$z↓2$.  But \MF\ has this formula built~in,
so we can use the bracket notation explicitly.

For example, let's go back to our first six example points, and suppose
that we want to refer to the point that's 2/5 of the way from
$z↓2=(100,100)$ to $z↓6=(200,0)$. In \MF\ we can write this simply as
$.4[z↓2,z↓6]$. And if we need to compute the exact coordinates for some
reason, we can always work them out from the general formula, getting
$z↓2+.4(z↓6-z↓2)=(100,100)+.4\bigl((200,0)-(100,100)\bigr)=(100,100)
+.4(100,-100)=(100,100)+(40,-40)=(140,60)$.

\exercise True or false: The direction vector from $(5,-2)$ to $(2,3)$
is $(-3,5)$.
\answer True; this is $(2,3)-(5,-2)$.

\exercise Explain what the notation `$0[z↓1,z↓2]$' means, if anything.
What about `$1[z↓1,z↓2]$'? And `$2[z↓1,z↓2]$'? And `$(-.5)[z↓1,z↓2]$'?
\answer $0[z↓1,z↓2]=z↓1$, because we move none of the way towards~$z↓2$;
similarly $1[z↓1,z↓2]$ simplifies to~$z↓2$, because we move all of the
way.  If we keep going in the same direction until we've gone twice as far
as the distance from $z↓1$ to~$z↓2$, we get to $2[z↓1,z↓2]$. But if we
start at point~$z↓1$ and face~$z↓2$, then back up exactly half the distance
between them, we wind up at $(-.5)[z↓1,z↓2]$.

\exercise True or false, for mathematicians: (a)~${1\over2}[z↓1,z↓2]=
{1\over2}(z↓1+z↓2)$; \ (b)~${1\over3}[z↓1,z↓2]={1\over3}z↓1+{2\over3}z↓2$;
\ (c)~$t[z↓1,z↓2]=(1-t)[z↓2,z↓1]$.
\answer (a)~True; both are equal to $z↓1+{1\over2}(z↓2-z↓1)$.
(b)~False, but close; the right-hand side should be
${2\over3}z↓1+{1\over3}z↓2$.  (c)~True; both are equal to $(1-t)z↓1+tz↓2$.

\setbox0=\vtop{\kern -6pt
  \rightline{\rlap{\vbox to 250\apspix{
        \setbox2=\vbox{\kern-1pt
          \hbox{\tenex\char'77} % vertical arrow extension module
          \kern-1pt}
	\offinterlineskip
        \vbox{\hbox{\tenex\char'170}\kern0pt} % arrowhead at top
        \cleaders\copy2\vfill
	\kern3pt
        \hbox to\wd2{\hss$b$\hss}
	\kern3pt
        \cleaders\copy2\vfill
        \vbox{\hbox{\tenex\char'171}\kern0pt} % arrowhead at bottom
        }}\kern 30\apspix
    \vbox{\kern-.2pt \hrule \kern-.2pt
      \hbox{\kern-.2pt \vrule \kern-.2pt
        \kern30\apspix\figbox{2e}{150\apspix}{250\apspix}\vbox
        \kern30\apspix\kern-.2pt\vrule \kern-.2pt}
      \kern-.2pt \hrule \kern-.2pt}\quad}
  \kern2pt
  \rightline{\hbox to 30\apspix{\kern-.2pt\vrule height 7pt depth 2pt
      \hfil$s$\hfil\vrule\kern-.2pt}%
    \hbox to 150\apspix{\leftarrowfill$\,a\,$\rightarrowfill}%
    \hbox to 30\apspix{\kern-.2pt\vrule height 7pt depth 2pt
      \hfil$s$\hfil\vrule\kern-.2pt}\quad}}
\dp0=0pt

\hangindent-300\apspix \hangafter-13
Let's conclude \strut\vadjust{\box0}%
this chapter by using mediation
to help specify the five points in the stick-figure `{\manual\Aa}'
shown enlarged at the right. The distance between points 1 and~5
should be~$a$, and point~3 should be $b$ pixels above the baseline;
these values $a$ and~$b$ have been predetermined by some method
that doesn't concern us here, and so has a ``↑{sidebar}'' parameter~$s$
that specifies the horizontal distance of points 1 and~5 from the
edges of the type. We shall assume that we don't know for sure what
the height of the bar line should be; point~2 should be somewhere on the
straight line from point~1 to point~3, and point~4 should be in the
corresponding place between 5 and~3, but we want to try several
possibilities before we make a decision.

The width of the character will be $s+a+s$, and we can specify points
$z↓1$ and $z↓5$ by the equations
\begindisplay
$"bot"\,z↓1=(s,0)$;\qquad $z↓5=z↓1+(a,0)$.
\enddisplay
There are other ways to do the job, but these formulas clearly express
our intention to have the bottom of the pen at the baseline, $s$ pixels
to the right of the reference point, when the pen is at~$z↓1$,
and to have $z↓5$ exactly $a$~pixels to the right of~$z↓1$.
Next, we can say
\begindisplay
$z↓3=\bigl({1\over2}[x↓1,x↓5],b\bigr)$;
\enddisplay
this means that the $x$ coordinate of point 3 should be halfway between
the $x$~coordinates of points 1 and~5, and that $y↓3=b$.  Finally, let's say
\begindisplay
$z↓2="alpha"[z↓1,z↓3]$;\qquad $z↓4="alpha"[z↓5,z↓3]$;
\enddisplay
the parameter "alpha" is a number between 0 and~1 that governs the
position of the bar line, and it will be supplied later. When "alpha"
has indeed received a value, we can say
\begindisplay
@draw@ $z↓1\to z↓3$;\qquad @draw@ $z↓3\to z↓5$;\qquad @draw@ $z↓2\to z↓4$.
\enddisplay
\MF\ will draw the characters `{\manual\sevenAs}' when "alpha" varies
from 0.2 to 0.5 in steps of 0.05 and when $a=150$, $b=250$, $s=30$.

\danger (Are you sure you should be reading this paragraph? The
``↑{dangerous bend}'' sign here is meant to warn you about material that
ought to be skipped on first reading. And maybe also on second reading.
The reader-beware paragraphs sometimes refer to concepts that aren't
explained until later chapters.)

\dangerexercise Why is it better to define $z↓3$ as shown above, rather
than to work out the coordinates $z↓3=(s+{1\over2}a,\,b)$ that are implied
by the other equations?
\answer There are several reasons. (1)~The equations in a \MF\ program
should represent the programmer's intentions as directly as possible;
it's hard to understand those intentions if you are shown only
their ultimate consequences, since it's not easy to reconstruct algebraic
manipulations that have gone on behind the scenes. (2)~It's easier and
safer to let the computer do algebraic calculations, rather than
to do them by hand. (3)~If the specifications for $z↓1$ and $z↓5$ change,
the formula $\bigl({1\over2}[x↓1,x↓5],b\bigr)$
still gives a reasonable value for~$z↓3$. It's
almost always good to anticipate the need for subsequent modifications.\par
However, the stated formula for $z↓3$ isn't the only reasonable way to
proceed. We could, for example, give two equations
\begindisplay
$x↓3-x↓1=x↓5-x↓3$;\qquad $y↓3=b$;
\enddisplay
the first of these states that the horizontal distance from 1 to 3 is
the same as the horizontal distance from 3 to~5. We'll see later that
\MF\ is able to solve a wide variety of equations.

\ninepoint	% all dangerous from here
\ddangerexercise Given $z↓1$, $z↓3$, and $z↓5$ as above, explain how
to define $z↓2$ and~$z↓4$ so that all of the following conditions hold:
\enddanger

\smallskip
\item\bull the line from $z↓2$ to $z↓4$ slopes upward at a $20↑\circ$ angle;

\item\bull the $y$ coordinate of that line's midpoint is 2/3 of the
way from $y↓3$ to $y↓1$;

\item\bull $z↓2$ and $z↓4$ are on the respective lines $z↓1\to z↓3$ and
$z↓3\to z↓5$.

\smallskip\noindent
(If you solve this exercise, you deserve an `{\manual\Az}'.)
\answer The following four equations suffice to define the four
unknown quantities $x↓2$, $y↓2$, $x↓4$, and $y↓4$:
$z↓4-z↓2="whatever"\times"dir"\,20$;
${1\over2}[y↓2,y↓4]={2\over3}[y↓3,y↓1]$;
$z↓2="whatever"[z↓1,z↓3]$;
$z↓4="whatever"[z↓3,z↓5]$. ↑↑"whatever" ↑↑{dir}

\endchapter

Here, where we reach the sphere of mathematics,
we are among processes which seem to some
the most inhuman of all human activities
and the most remote from poetry.
Yet it is here that the artist has the fullest scope for his imagination.
\author HAVELOCK ↑{ELLIS}, {\sl The Dance of Life\/} (1923) % pp 138--139

\bigskip

I haven't kept score, but I would say that
of the two hundred or so books he ↑↑{Wolfe, Nero} reads in a year
not more than five or six get an A.
\author REX ↑{STOUT}, {\sl Plot It Yourself\/\kern-1pt} (1959) % 1st paragraph

\eject
\beginchapter Chapter 3. Curves

Albrecht ↑{D\"urer} and other Renaissance men attempted to establish
mathematical principles of type design, but the letters they came up with
were not especially beautiful. Their methods failed because they
restricted themselves to ``ruler and compass'' constructions, which cannot
adequately express the nuances of good calligraphy. \MF\ gets around this
problem by using more powerful mathematical techniques, which provide the
necessary flexibility without really being too complicated. The purpose of
the present chapter is to explain the simple principles by which a
computer is able to draw ``pleasing'' ↑{curves}.

The basic idea is to start with four points $(z↓1,z↓2,z↓3,z↓4)$ and to
↑↑{four-point method for curves}
construct the three ↑{midpoints} $z↓{12}={1\over2}[z↓1,z↓2]$,
$z↓{23}={1\over2}[z↓2,z↓3]$, $z↓{34}={1\over2}[z↓3,z↓4]$:
\displayfig 3a (5pc)
Then take those three midpoints $(z↓{12},z↓{23},z↓{34})$ and construct
two second-order midpoints $z↓{123}={1\over2}[z↓{12},z↓{23}]$ and
$z↓{234}={1\over2}[z↓{23},z↓{34}]$; finally, construct the third-order
midpoint $z↓{1234}={1\over2}[z↓{123},z↓{234}]$:
\displayfig 3b (5pc)
This point $z↓{1234}$ is one of the points of the curve determined by
$(z↓1,z↓2,z↓3,z↓4)$. To get the remaining points of that curve,
repeat the same construction on $(z↓1,z↓{12},z↓{123},z↓{1234})$ and
on $(z↓{1234},z↓{234},z↓{34},z↓4)$, ad infinitum:
\displayfig 3c (4.5pc)
The process converges quickly, and the preliminary scaffolding
(which appears above the limiting curve in our example) is ultimately discarded.
The limiting curve has the following important properties:

\smallskip
\item\bull It begins at $z↓1$, heading in the direction from $z↓1$ to $z↓2$.

\item\bull It ends at $z↓4$, heading in the direction from $z↓3$ to $z↓4$.

\item\bull It stays entirely within the so-called convex hull of $z↓1$,
$z↓2$, $z↓3$, and $z↓4$; i.e., all points of the curve lie ``between'' the
defining points.

\danger The curve defined by these recursive rules can be described
algebraically by the remarkably simple formula
\begindisplay
$z(t)\;=\;(1-t)↑3z↓1+3(1-t)↑2t\,z↓2+3(1-t)t↑2z↓3+t↑3z↓4$,
\enddisplay
as the parameter $t$ varies from 0 to 1. This polynomial of degree~3 in~$t$
is called a {\sl ↑{Bernshte{\u\i}n polynomial}}, because Serge\u\i~N.
↑{Bernshte{\u\i}n} introduced such functions in 1912 as part of his
pioneering work on approximation theory. Curves traced out by Bernshte{\u\i}n
polynomials of degree~3 are often called {\sl B\'ezier cubics}, after
Pierre ↑{B\'ezier} who realized their importance for computer-aided design
during the 1960s.

\danger It is interesting to observe that the Bernshte\u\i n polynomial
of degree~1, i.e., the function $z(t)=(1-t)\,z↓1+t\,z↓2$, is precisely the
↑{mediation} operator $t[z↓1,z↓2]$ that we discussed in the previous chapter.
Indeed, if the geometric construction we have just seen is changed to
use $t$-of-the-way points instead of midpoints (i.e., if $z↓{12}=
t[z↓1,z↓2]$ and $z↓{23}=t[z↓2,z↓3]$, etc.), then $z↓{1234}$ turns out
to be precisely $z(t)$ in the formula above.

No matter what four points $(z↓1,z↓2,z↓3,z↓4)$ are given, the construction
on the previous page defines a curved line that runs from $z↓1$ to~$z↓4$.
This curve is not always interesting or beautiful; for example, if all
four of the given points lie on a straight line, the entire ``curve''
that they define will also be contained in that same line. We obtain
rather different curves from the same four starting points if we
number the points differently:
\displayfig 3d (8pc)
Some discretion is evidently advisable when the $z$'s are chosen. But the
four-point method is good enough to obtain satisfactory approximations to
any curve we want, provided that we break the desired curve into short
enough segments and give four suitable control points for each segment.
It turns out, in fact, that we can usually get by with only a few segments.
For example, the four-point method can produce an approximate
quarter-circle with less than 0.06\% error; it never yields an exact
circle, but the differences between four such quarter-circles and a true
circle are imperceptible.

All of the curves that \MF\ draws are based on four points, as just
described. But it isn't necessary for a user to specify all of those
points, because the computer is usually able to figure out good values of
$z↓2$ and $z↓3$ by itself. Only the endpoints $z↓1$ and~$z↓4$, through
which the curve is actually supposed to pass, are usually mentioned
explicitly in a \MF\ program.

For example, let's return to the six points that were used to introduce the
ideas of coordinates in Chapter~2. We said `@draw@ $z↓1\to z↓6$' in that
chapter, in order to draw a straight line from point~$z↓1$ to point~$z↓6$.
In general if three or more points are listed instead of two, \MF\ will draw a
↑↑{..} smooth curve through those points. For example, the commands
`@draw@ $z↓4\to z↓1\to z↓2\to z↓6$' and `@draw@ $z↓5\to z↓4\to z↓1
\to z↓3\to z↓6\to z↓5$' will produce the respective results
\displayfig 3e (7.75pc)
(Unlabelled points in these diagrams are ↑{control points} that \MF\ has
supplied automatically so that it can use the four-point scheme to draw
curves between each pair of adjacent points on the specified paths.)

Notice that the curve is not smooth at $z↓5$ in the right-hand example,
because $z↓5$~appears at both ends of that particular path. In order to
get a completely smooth curve that returns to its starting point, you can
say `@draw@ $z↓5\to z↓4\to z↓1\to z↓3\to z↓6\to \cycle$' instead:
\displayfig 3f (7.25pc)
The word `↑{cycle}' at the end of a path refers to the starting point
of that path.
\MF\ believes that this ↑{bean-like shape}
is the nicest way to connect the given points in the given cyclic order;
but of course there are many decent curves that satisfy the specifications,
and you may have another one in mind. You can obtain finer control
by giving hints to the machine in various ways. For example, the
bean curve can be ``pulled tighter'' between $z↓1$ and~$z↓3$ if you say
\begindisplay
@draw@ $z↓5\to z↓4\to z↓1\to\tension1.2\to z↓3\to z↓6\to \cycle$;
\enddisplay
the so-called ↑{tension} between points is normally 1, and an increase
to 1.2 yields
\displayfig 3g (5.75pc)

\danger An unsymmetrical effect can be obtained by increasing the tension
only at point~1 but not at points 3~or~4; the shape
\displayfig 3h (6.5pc)
comes from
%\begindisplay
%@draw@ $z↓5\to z↓4\to\tension1\and1.5\to z↓1\to
%  \tension1.5\and1\to z↓3$\cr
%\hskip6em$\to z↓6\to \cycle$.
%\enddisplay
`@draw@ $z↓5\to z↓4\to\tension1\and1.5\to z↓1\to
 \tension1.5\and1\to z↓3\to z↓6\to \cycle$'.
The effect of tension has been achieved in this example by moving two of
the anonymous control points closer to point~1.

It's possible to control a curve in another way, by telling \MF\ what direction to
travel at some or all of the points. Such directions are given inside
curly braces; for example,
\begindisplay
@draw@ $z↓5\to z↓4\{"left"\}\to z↓1\to z↓3\to z↓6\{"left"\}\to\cycle$
\enddisplay
says that the curve should be traveling leftward at points 4 and 6. The
resulting curve is perfectly straight from $z↓6$ to~$z↓5$ to~$z↓4$:
\displayfig 3i (5.8pc)
We will see later that `"left"' is an abbreviation for the vector $(-1,0)$,
which stands for one unit of travel in a leftward direction. Any desired
direction can be specified by enclosing a vector in $\{\ldots\}$'s; for
example, the command `@draw@ $z↓4\to z↓2\{z↓3-z↓4\}\to z↓3$' will draw a
curve from $z↓4$ to~$z↓2$ to~$z↓3$ such that the tangent direction at
$z↓2$ is parallel to the line $z↓4\to z↓3$, because $z↓3-z↓4$ is the
vector that represents travel from $z↓4$ to~$z↓3$:
\displayfig 3j (4.7pc)
The same result would have been obtained from a command such as `@draw@
$z↓4\to z↓2 \{10(z↓3-z↓4)\}\to z↓3$', because the vector $10(z↓3-z↓4)$ has
the same direction as $z↓3-z↓4$. \MF\ ignores the magnitudes of vectors
when they are simply being used to specify directions.

\exercise What do you think will be the result of
`@draw@ $z↓4\to z↓2\{z↓4-z↓3\}\to z↓3$', when points $z↓2$, $z↓3$,~$z↓4$
are the same as they have been in the last several examples?
\answer The direction at $z↓2$ is parallel to the line $z↓4\to z↓3$, but
the vector $z↓4-z↓3$ specifies a direction towards $z↓4$, which is
$180↑\circ$ different from the direction $z↓3-z↓4$ that was discussed in
the text. Thus, we have a difficult specification to meet, and \MF\ draws
a pretzel-shaped curve that loops around in a way that's too ugly to show
here. The first part of the path, from $z↓4$ to $z↓2$, is mirror symmetric
about the line~$z1\to z5$ that bisects $z↓4\to z↓2$, so it starts out in a
south-by-southwesterly direction; the second part is mirror symmetric about
the vertical line that bisects $z↓2\to z↓3$, so when the curve ends at~$z↓3$
it's traveling roughly northwest. The moral is: Don't specify a direction
that runs opposite to (i.e., is the negative of) the one you really want.

\exercise Explain how to get \MF\ to draw the wiggly shape
\displayfig 3k (5pc)
in which the curve aims directly at point 2 when it's at point~6, but
directly away from point~2 when it's at point~4. [{\sl Hint:\/} No
tension changes are needed; it's merely necessary to specify directions
at $z↓4$ and~$z↓6$.]
\answer @draw@ $z↓5\to z↓4\{z↓4-z↓2\}\to z↓1\to z↓3\to z↓6\{z↓2-z↓6\}
\to\cycle$.

\MF\ allows you to change the shape of a curve at its endpoints by
specifying different amounts of ``↑{curl}.'' For example, the two commands
\begindisplay
@draw@ $z↓4\{\curl0\}\to z↓2\{z3-z4\}\to\{\curl0\}\,z↓3$;\cr
@draw@ $z↓4\{\curl2\}\to z↓2\{z3-z4\}\to\{\curl2\}\,z↓3$\cr
\enddisplay
give the respective curves
\displayfig 3l (5pc)
which can be compared to the one shown earlier when no special curl was
requested. \ (The specification `$\curl1$' is assumed at an endpoint
if no explicit curl or direction has been mentioned, just as
`$\tension1$' is implied between points when no tension has
been explicitly given.) \ Chapter 14 explains more about~this.

It's possible to get curved lines instead of straight lines even when
only two points are named, if a direction has been prescribed at one or
both of the points. For example,
\begindisplay
@draw@ $z↓4\{z↓2-z↓4\}\to\{"down"\}\,z↓6$\cr
\enddisplay
asks \MF\ for a curve that starts traveling towards $z↓2$ but finishes
in a downward direction:
\displayfig 3m (4pc)

\danger Here are some of the curves that \MF\ draws between two points, when
it is asked to move outward from the left-hand point at an angle of
$60↑\circ$, and to approach the right-hand point at various different angles:
\displayfig 3aa (2.6cm)
This diagram was produced by the \MF\ program ↑↑@for@ ↑↑@step@ ↑↑@until@ ↑↑"cm"
\begindisplay
@for@ $d=0$ @step@ 10 @until@ 120:\cr
\indent @draw@ $(0,0)\{"dir"\,60\}\to\{"dir"\,{-d}\}(6"cm",0)$; @endfor@\cr
\enddisplay
the `↑"dir"\!' function specifies a direction measured in degrees
counterclockwise from a horizontal rightward line, hence `$"dir"\,{-d}$'
gives a direction that is $d↑\circ$ below the horizon.  The lowest curves
in the illustration correspond to small values of $d$, and the highest
curves correspond to values near $120↑\circ$.

\danger A car that drives along the upper paths in the diagram above
is always turning to the right, but in the lower paths it comes to a
point where it needs to turn to the left in order to reach its destination
from the specified direction.
The place where a path changes its curvature from right to left or
vice versa is called an ``↑{inflection point}.'' \MF\ introduces
inflection points when it seems better to change the curvature than
to make a sharp turn; indeed, when $d$ is negative there is no way to
avoid points of inflection, and the curves for small positive~$d$ ought to
be similar to those obtained when $d$~has small negative values. The program
\begindisplay
@for@ $d=0$ @step@ $-10$ @until@ $-90$:\cr
\indent @draw@ $(0,0)\{"dir"\,60\}\to\{"dir"\,{-d}\}(6"cm",0)$; @endfor@\cr
\enddisplay
shows what \MF\ does when $d$ is negative:
\displayfig 3bb (2.8cm)

\danger It is sometimes desirable to avoid points of inflection, when $d$ is
positive, and to require the curve to remain inside of the triangle
determined by its initial and final directions. This can be achieved
↑↑{...}
by using three dots instead of two when you specify a curve: The program
\begindisplay
@for@ $d=0$ @step@ 10 @until@ 120:\cr
\indent @draw@ $(0,0)\{"dir"\,60\}\ldots\{"dir"\,{-d}\}(6"cm",0)$; @endfor@\cr
\enddisplay
generates the curves
\displayfig 3cc (2.6cm)
which are the same as before except that inflection points do not occur
for the small values of~$d$. A `$\ldots$' specification keeps the
curve ``↑{bounded}'' inside the triangle that is defined by the endpoints
and directions; but it has no effect when there is
no such triangle.  More precisely, suppose that the curve goes from $z↓0$
to~$z↓1$; if there's a point~$z$ such that the initial direction is from
$z↓0$ to~$z$ and the final direction is from $z$ to~$z↓1$, then the curve
specified by `$\ldots$' will stay entirely within the triangle whose
corners are at $z↓0$, $z↓1$, and~$z$. But if there's no such triangle
(e.g., if $d<0$ or $d>120$ in our example program), both `$\ldots$'
and~`$\to$' will produce the same curves.

In this chapter we have seen lots of different ways to get \MF\ to draw
curves.  And there's one more way, which subsumes all of the others.
If changes to tensions, curls, directions, and/or boundedness
aren't enough to produce the sort of curve that a person wants, it's
always possible as a last resort to specify all four of the points in the
four-point method.  For example, the command
\begindisplay
@draw@ $z↓4\to\controls z↓1\and z↓2\to z↓6$
\enddisplay
will draw the following curve from $z↓4$ to $z↓6$:↑↑{controls}
\displayfig 3n (5pc)


\endchapter

And so I think I have omitted nothing
% Et ainsi ie pense n'auoir rien omis des elemens,
that is necessary to an understanding of curved lines.
% qui sont necessaires pour la connoissance des lignes courbes.
\author REN\'E ↑{DESCARTES}, {\sl La G\'eom\'etrie\/} (1637) % p369

\bigskip

A second quotation.
\author A SECOND AUTHOR, {\sl A Second Title\/} (1776)

\eject
\beginchapter Chapter 4. Pens

Our examples so far have involved straight lines or curved lines that look
as if they were drawn by a felt-tip ↑{pen}, where the ↑{nib} of that pen
was perfectly round.  A mathematical ``line'' has no thickness, so it's
invisible; but when we plot circular dots at each point of an infinitely
thin line, we get a visible line that has constant thickness.

Lines of constant thickness have their uses, but \MF\ also provides
several other kinds of scrivener's tools, and we shall take a look at some
of them in this chapter. We'll see not only that the sizes and shapes of
pen nibs can be varied, but also that characters can be built up in such a
way that the outlines of each stroke are precisely controlled.

\def\kk{\kern2pt } % kidney-bean kern
First let's consider the simplest extensions of what we have seen before.
The letter `{\manual\Aa}' of Chapter~2 and the kidney-↑{bean}
`\kk{\manual\beana}\kk' of Chapter~3 were drawn with circular pen nibs of
diameter $0.4\pt$, where `pt' stands for a printer's point;\footnote*{$
1\,{\rm in}=2.54\,{\rm cm}=72.27\pt$ exactly, as explained in
{\sl The \TeX book}.} $0.4\pt$ is the standard thickness of a ruled line
`$\,\vcenter{\hrule width 2em}\,$' drawn by \TeX. Such a penpoint can be
specified by telling \MF\ to
\begindisplay
\pickup @pencircle@ ↑{scaled} $0.4"pt"$;
\enddisplay
\MF\ will use the pen it has most recently picked up ↑↑@pickup@
whenever it is asked to `↑@draw@' anything. A ↑@pencircle@ is a
circular pen whose diameter is the width of one pixel. Scaling it
by $0.4"pt"$ will change it to the size that corresponds
to $0.4\pt$ in the output, because ↑"pt" is the number of pixels
in $1\pt$. If the key points $(z↓1,z↓2,z↓3,z↓4,z↓5,z↓6)$ of Chapters 2 and~3
have already been defined, the \MF\ commands
\begindisplay
\pickup @pencircle@ scaled $0.8"pt"$;\cr
@draw@ $z↓5\to z↓4\to z↓1\to z↓3\to z↓6\to \cycle$\cr
\enddisplay
will produce a bean shape twice as thick as before: `\kk{\manual\beanb}\kk'
instead of `\kk{\manual\beana}\kk'.

More interesting effects arise when we use non-circular pen nibs. For example,
the command
\begindisplay
\pickup @pencircle@ ↑{xscaled} $0.8"pt"$ ↑{yscaled} $0.2"pt"$
\enddisplay
picks up a pen whose tip has the shape of an ellipse, $0.8\pt$ wide and
$0.2\pt$ tall; magnified 10 times, it looks like this:
`$\,\vcenter{\hbox{\manual\niba}}\,$'.
\ (The operation of ``xscaling'' multiplies $x$~coordinates by a specified
amount but leaves $y$~coordinates unchanged, and the operation of
``yscaling'' is similar.) \ Using such a pen, the `\kk{\manual\beana}\kk'
becomes `\kk{\manual\beanc}\kk', and `{\manual\Aa}' becomes `{\manual\Ab}'.
Furthermore,
\begindisplay
\pickup @pencircle@ xscaled $0.8"pt"$ yscaled $0.2"pt"$ ↑{rotated} 30
\enddisplay
takes that ellipse and rotates it $30↑\circ$ counterclockwise, obtaining the nib
`$\vcenter{\hbox{\manual\nibb}}$'; this changes `\kk{\manual\beanc}\kk' into
`\kk{\manual\beand}\kk' and `{\manual\Ab}' into `{\manual\Ac}'. An
enlarged view of the bean shape shows more clearly what is going on:
\displayfig 4a (7pc)
The right-hand example was obtained by eliminating the clause
`yscaled~$0.2"pt"$'; this makes the pen almost razor thin, only
one pixel tall before rotation.

\exercise Describe the pen shapes defined by
(a)~@pencircle@ xscaled~$0.2"pt"$ yscaled~$0.8"pt"$;
\ (b)~@pencircle@ scaled~$0.8"pt"$ rotated~30;
\ (c)~@pencircle@ xscaled~.25 scaled~$0.8"pt"$.
\answer (a)~An ellipse $0.8\pt$ tall and $0.2\pt$ wide
(`$\,\vcenter{\hbox{\manual\nibc}}\,$');
\ (b)~A~circle of diameter $0.8\pt$ (rotation doesn't change a circle!);
\ (c)~same as~(a).

\exercise We've seen many examples of `↑@draw@'
used with two or more points. What do you think \MF\ will do
if you ask it to perform the following commands?
\begindisplay
@draw@ $z↓1$;\ @draw@ $z↓2$; \ @draw@ $z↓3$; \ @draw@ $z↓4$;
 \ @draw@ $z↓5$; \ @draw@ $z↓6$.
\enddisplay
\answer Six individual points will be drawn, instead of lines or curves.
These points will be drawn with the current pen. However, for technical
reasons explained in Chapter~xx, the @draw@ command does its best work when it
is moving the pen; the pixels you get at the endpoints of curves are
not always what you would expect, especially at low resolutions. It is
usually best to say `↑@drawdot@' instead of `@draw@' when you are drawing
only ↑{one point}.

\def\hidecoords(#1,#2){\hbox to 0pt{\hss$\scriptstyle(#1,#2)$\hss}}
\setbox0=\vtop{\kern 42pt
  \rightline{\vbox{\hbox to 208\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern3pt
      \figbox{4b}{208\apspix}{216\apspix}\vbox
      \kern-3pt
      \hbox to 208\apspix{\hidecoords(0,0)\hfil\hidecoords(w,0)}}\quad}}
\dp0=0pt

\hangindent-125pt \hangafter4
\indent\strut\vadjust{\box0}%
Let's turn now to the design of a real letter that has already appeared
many times in this manual, namely the `\thinspace{\manual ↑{T}}\thinspace' of
`\MF'. All seven of ↑↑{METAFONT logo} the distinct letters in `\MF' will
be used to illustrate various ideas as we get into the details of the
language; we might as well start with~`\thinspace{\manual T}\thinspace',
because it occurs twice, and (especially) because it's the simplest. An
enlarged version of this letter is shown at the right of this paragraph,
including the locations of its four key points $(z↓1,z↓2,z↓3,z↓4)$ and its
↑{bounding box}. Typesetting systems like \TeX\ are based on the
assumption that each character fits in a rectangular ↑{box}; we shall
discuss boxes in detail later, but for now we will be content simply to
know that such boundaries do exist.\footnote*{Strictly speaking, the
bounding box doesn't strictly have to ``bound'' the black pixels of a
character; for example, the `\thinspace{\manual q}\thinspace' protrudes
slightly below the baseline at point~4, and italic letters frequently
extend rather far to the right of their boxes. However, \TeX\ positions
all characters by lumping boxes together as if they were pieces of metal
type that contain all of the ink.} Numbers $h$ and~$w$ ↑↑"h" ↑↑"w" will
have been computed so that the corners of the box are at positions
$(0,0)$, $(0,h)$, $(w,0)$, and~$(w,h)$ as shown.

\hangindent-125pt
\hangafter\prevgraf \advance\hangafter by -16 % 4+12 (12 lines for the figure)
Each of the letters in `\MF' is drawn with a pen whose nib is an unrotated
ellipse, 90\% as tall as it is wide. In the 10-point size, which is used
for the main text of this book, the pen is $2/3\pt$ wide, so it has
been specified by the command
\begindisplay
\pickup @pencircle@ scaled $2\over3$"pt" yscaled $9\over10$
\enddisplay
or something equivalent to this.

We shall assume that a special value `$o$' has been computed so that the
bottom of the vertical stroke in `\thinspace{\manual T}\thinspace' should
descend exactly $o$~pixels below the baseline; ↑↑"o" this is called the
amount of ``↑{overshoot}.'' Given $h$, $w$, and~$o$, it is a simple matter
to define the four key points and to draw the
`\thinspace{\manual T}\thinspace':  ↑↑"top" ↑↑"lft" ↑↑"rt" ↑↑"bot"
\begindisplay
$"top"\,"lft"\,z↓1=(0,h)$; \quad $"top"\,"rt"\,z↓2=(w,h)$;\cr
$"top"\,z↓3=(.5w,h)$; \quad $"bot"\,z↓4=(.5w,-o)$;\cr
@draw@ $z↓1\to z↓2$; \quad @draw@ $z↓3\to z↓4$.\cr
\enddisplay

\danger Sometimes it is easier and/or clearer to define the $x$ and~$y$
↑{coordinates} separately. For example, the key points of
the~`\thinspace{\manual j}\thinspace'
could also be specified thus:
\begindisplay
$"lft"\,x↓1=0$;&$w-x↓2=x↓1$;&$x↓3=x↓4=.5w$;\cr
$"top"\,y↓1=h$;&$"bot"\,y↓4=-o$;&$y↓1=y↓2=y↓3$.\cr
\enddisplay
The equation $w-x↓2=x↓1$ expresses the fact that $x↓2$ is just as far from
the right edge of the bounding box as $x↓1$ is from the left edge.

\danger What exactly does `"top"\!' mean in a \MF\ equation? If the
currently-picked-up pen extends $l$~pixels to the left of its center,
$r$~pixels to the right, $t$~pixels upward and $b$~downward, then
\begindisplay
$"top"\,z=z+(0,t)$,\kern-1em&$"bot"\,z=z-(0,b)$,\kern-1em&
$"lft"\,z=z-(l,0)$,\kern-1em&$"rt"\,z=z+(r,0)$,\cr
\noalign{\vskip\belowdisplayskip
\vbox{\noindent\strut
when $z$ is a pair of coordinates. But---as the previous paragraph
shows, if you study it carefully---we also have
\strut}\vskip\abovedisplayskip}
$"top"\,y=y+t$,&$"bot"\,y=y-b$,&
$"lft"\,x=x-l$,&$"rt"\,x=x+r$,\cr
\enddisplay
when $x$ and $y$ are single values instead of coordinate pairs.
You shouldn't apply `"top"\!' or `"bot"\!' to $x$~coordinates,
nor `"lft"\!' or `"rt"\!' to $y$~coordinates.

\dangerexercise True or false: $"top"\,"bot"\,z=z$, whenever $z$
is a pair of coordinates.
\answer True, for all of the pens discussed so far. But false in general,
since we will see later that pens might extend further upward than
downward; i.e., $t$~might be unequal to~$b$ in the equations for
"top" and "bot".

\setbox0=\vtop{\kern -12pt
  \rightline{\vbox{\hbox to 288\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern3pt
      \figbox{4c}{288\apspix}{216\apspix}\vbox
      \kern-3pt
      \hbox to 288\apspix{\hidecoords(0,0)\hfil\hidecoords(w,0)}}\quad}}
\dp0=0pt
\begingroup\decreasehsize 165pt
\dangerexercise An enlarged \strut\vadjust{\box0}%
picture of \MF's `{\manual h}' shows that it has five key points. Assuming ↑↑{M}
that special values $ss$ and~"ygap" have been precomputed and that the equations
\begindisplay
$x↓1=ss$;\quad$y↓3="ygap"$;\quad$w-x↓5=x↓1$\cr
\enddisplay
have already been given, what further equations and `@draw@' ↑↑{METAFONT
logo} commands will complete the specification of this letter? \ (The
value of~$w$ will be greater for~`\thinspace{\manual h}\thinspace' than it was
for~`\thinspace{\manual j}\thinspace'; it
stands for the pixel width of whatever character is currently being drawn.)
\answer $x↓2=x↓1$; $x↓3={1\over2}[x↓2,x↓4]$; $x↓4=x↓5$; $"bot"\,y↓1=-o$;
$"top"\,y↓2=h+o$; $y↓4=y↓2$; $y↓5=y↓1$; @draw@ $z↓1\to z↓2$;
@draw@ $z↓2\to z↓3$; @draw@ $z↓3\to z↓4$; @draw@ $z↓4\to z↓5$.
We will learn later that the four @draw@ commands can be replaced by
\begindisplay
@draw@ $z↓1\dashto z↓2\dashto z↓3\dashto z↓4\dashto z↓5$;
\enddisplay
in fact, this will make \MF\ run slightly faster. ↑↑{--}

\endgroup % end of the diminished \hsize

\MF's ability to `@draw@' allows it to produce character shapes that are
satisfactory for many applications, but the shapes are inherently limited
by the fact that the simulated pen nib must stay the same through an
entire stroke. Human penpushers are able to get richer effects by
using different amounts of pressure and/or by rotating the pen as they draw.

We can obtain finer control over the characters we draw if we specify
their outlines, instead of working only with key points that lie somewhere
in the middle.  In fact, \MF\ works internally with outlines, and the
computer finds it much easier to fill a region with solid black than to
figure out what pixels are blackened by a moving pen. There's a `↑@fill@'
command that does region filling; for example, the solid ↑{bean} shape
\displayfig 4d (6.5pc)
can be obtained from our six famous example points by giving the command
\begindisplay
@fill@ $z↓5\to z↓4\to z↓1\to z↓3\to z↓6\to \cycle$.
\enddisplay
The region that is filled is essentially what would be cut out by an
infinitely sharp ↑{knife} blade if it traced over the given curve while
cutting a piece of thin film. A @draw@ command needs to add thickness to
its curve, because the result would otherwise be invisible; but a @fill@
command adds no thickness.

The curve in a @fill@ command must end with `↑{cycle}', because an
entire region must be filled. It wouldn't make sense to say, e.g.,
`@fill@ $z↓1\to z↓2$'. The cycle being filled shouldn't cross itself,
either; \MF\ would have lots of trouble trying to figure out how to
obey a command like `@fill@ $z↓1\to z↓6\to z↓3\to z↓4\to\cycle$'.

\dangerexercise Chapter 3 discusses the curve $z↓5\to z↓4\to z↓1\to
z↓3\to z↓6\to z↓5$, which isn't smooth at~$z↓5$. Since this curve
doesn't end with `cycle', you can't use it in a @fill@ command.
But it does define a closed region. How can \MF\ be instructed
to fill that region?
\answer Either say `@fill@ $z↓5\to z↓4\to z↓1\to z↓3\to z↓6\to z↓5\to
\cycle$', which doubles point~$z↓5$ and abandons smoothness there,
or `@fill@ $z↓5\{\curl1\}\to z↓4\to z↓1\to z↓3\to z↓6\to
\{\curl1\}\cycle$'. In the latter case you can omit either one of
the ↑{curl} specifications, but not both.

The black ↑{triangle} `{\manual\char'170}' that appears in the statement of
exercises in this book was drawn with the command
\begindisplay
@fill@ $z↓1\dashto z↓2\dashto z↓3\dashto\cycle$
\enddisplay
after appropriate corner points $z↓1$, $z↓2$, and $z↓3$ had been specified.
In this case the outline of the region to be filled was specified in terms
of the symbol `$\dashto$' instead of `$\to$'; ↑↑{--}↑↑{..}
this is a convention we haven't discussed before. Each `$\dashto$'
introduces a straight line segment, which is independent of the rest of
↑↑{polygonal path}
the path that it belongs to; thus it is quite different from `$\to$', which
specifies a possibly curved line segment that connects smoothly with neighboring
points and lines of a path. In this case `$\dashto$' was used so that the
triangular region would have straight edges and sharp corners. We might say
informally that `$\to$' means ``Connect the points with a nice curve,''
while `$\dashto$' means ``Connect the points with a straight line.''

\setbox0=\vtop{\kern -9pt
  \rightline{\vbox{\hbox to 180\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern3pt
      \figbox{4e}{180\apspix}{225\apspix}\vbox
      \kern-3pt
      \hbox to 180\apspix{\hidecoords(0,0)\hfil\hidecoords(w,0)}}\quad}}
\dp0=0pt
\begingroup\decreasehsize 111pt

\danger \strut\vadjust{\box0}%
The corner points $z↓1$, $z↓2$, and $z↓3$ were defined carefully
so that the triangle would be {\sl↑{equilateral}}, i.e., so that all three
of its sides would have the same length. Since an equilateral triangle
has $60↑\circ$ angles, the following equations did the job:
\begindisplay
$x↓1=x↓2=w-x↓3=s$;\cr
$y↓3=.5h$;\cr
$z↓1-z↓2=(z↓3-z↓2)$ ↑{rotated} 60.\cr
\enddisplay
Here $w$ and $h$ represent the character's width and height, and $s$~is
the distance of the triangle from the left and right edges of the type.

\endgroup % end of the diminished \hsize

\danger The @fill@ command has a companion called ↑@unfill@, which changes
pixels from black to white inside a given region. For example, the solid
bean shape on the previous page can be changed to
\displayfig 4f (6.5pc)
if we say also `@unfill@ ${1\over4}[z↓4,z↓2]\to{3\over4}[z↓4,z↓2]\to\cycle$;
\ @unfill@ ${1\over4}[z↓6,z↓2]\to{3\over4}[z↓6,z↓2]\to\cycle$'.
This example shows, incidentally, that \MF\ converts a two-point specification
like `$z↓1\to z↓2\to\cycle$' into a more-or-less circular path, even though
two points by themselves define only a straight line.

\dangerexercise Let $z↓0$ be the point $(.8[x↓1,x↓2],.5[y↓1,y↓4])$,
and introduce six new points by letting $z'↓k=.2[z↓k,z↓0]$ for $k=1,$ 2,
\dots,~6. Explain how to obtain the shape
\displayfig 4g (7.0pc)
in which the interior region is defined by $z'↓1\ldots z'↓6$ instead of
by $z↓1\ldots z↓6$.
\answer After the six original points have been defined, say
\begindisplay
@fill@ $z↓5\to z↓4\to z↓1\to z↓3\to z↓6\to\cycle$;\cr
$z↓0=(.8[x↓1,x↓2],.5[y↓1,y↓4])$;\cr
@for@ $k=1$ @upto@ 6: $z↓k'=.2[z↓k,z↓0]$; @endfor@\cr
@unfill@ $z↓5'\to z↓4'\to z↓1'\to z↓3'\to z↓6'\to\cycle$.\cr
\enddisplay

The ability to fill between outlines makes it possible to pretend that we
have ↑{broad-edge pens} that change in direction and pressure as they
glide over the paper, if we consider the separate paths traced out by the
pen's left edge and right edge.  For example, the stroke
\displayfig 4h (3pc)
can be regarded as drawn by a pen that starts at the left, inclined
at a $30↑\circ$ angle; as the pen moves, it turns gradually until its
↑↑{angle of pen} edge is strictly vertical by the time it reaches the
right end. The pen motion was horizontal at positions 2 and~3. This stroke
was actually obtained by the command
\begindisplay
@fill@ $z↓{1l}\to z↓{2l}\{"right"\}\to\{"right"\}\,z↓{3l}$\cr
$\hskip4em\dashto z↓{3r}\{"left"\}\to\{"left"\}\,z↓{2r}\to z↓{1r}$\cr
$\hskip4em\dashto\cycle$;
\enddisplay
i.e., \MF\ was asked to fill a region bounded by a ``left path'' from
$z↓{1l}$ to $z↓{2l}$ to $z↓{3l}$, followed by a straight line ↑↑{--}
to~$z↓{3r}$, then a reversed ``right path'' from $z↓{3r}$ to $z↓{2r}$ to
$z↓{1r}$, and finally a straight line back to the starting point~$z↓{1l}$.

Key positions of the ``pen'' are represented in this example by sets of
three points, like $(z↓{1l},z↓1,z↓{1r})$, which stand for the pen's left edge,
its midpoint, and its right edge. The midpoint doesn't actually occur in the
specification of the outline, but we'll see examples of its usefulness.
The relationships between such triples of points are established by a
`↑"penpos"' command, which states the breadth of the pen and its angle of
inclination at a particular position.  For example, positions 1, 2, and~3
in the stroke above were established by saying
\begindisplay
$\penpos1(1.2"pt",30)$;&
$\penpos2(1.0"pt",45)$;&
$\penpos3(0.8"pt",90)$;\cr
\enddisplay
this made the pen $1.2\pt$ broad and tipped $30↑\circ$ with respect to
the horizontal at position~1, etc. In general the idea is to specify
\begindisplay
$\penpos k(b,d)$
\enddisplay
where $k$ is the position number or position name, $b$ is the breadth (in
pixels), and $d$~is the angle (in degrees). Pen angles are measured
counterclockwise from the horizontal. Thus an angle of 0 makes the right
edge of the pen exactly $b$~pixels to the right of the left edge; an angle
of 90 makes the right pen edge exactly $b$~pixels above the left; an angle
of~$-90$ makes it exactly $b$~pixels below. An angle of 45 makes the right
edge $b/{\sqrt2}$ pixels above and $b/{\sqrt2}$ pixels to the right of the
left edge; an angle of~$-45$ makes it $b/{\sqrt2}$ pixels below and
$b/{\sqrt2}$ to the right. When the pen angle is between $90↑\circ$ and
$180↑\circ$, the ``right'' edge actually lies to the left of the ``left''
edge. In terms of ↑{compass directions} on a conventional map, an angle
of~$0↑\circ$ points due East, while $90↑\circ$ points North and $-90↑\circ$
points South. The angle corresponding to Southwest is $-135↑\circ$,
also known as $+225↑\circ$.

\exercise What angle corresponds to the direction North by Northwest?
\answer ${1\over2}\bigl["North",{1\over2}["North","West"]\bigr]=
{1\over2}\bigl[90,{1\over2}[90,180]\bigr]={1\over2}[90,135]=112.5$.

\begingroup \decreasehsize 9pc
\exercise \xdef\circlex{4.\number\exno}%
\rightfig 4i (7pc x 7pc) ↑20pt
What are the pen angles at positions 1, 2, 3, and~4 in
the circular shape shown here? [{\sl Hint:\/} Each angle is a multiple
of $30↑\circ$. Note that $z↓{3r}$ lies to the left of $z↓{3l}$.]
\answer $30↑\circ$, $60↑\circ$, $210↑\circ$, and $240↑\circ$. Since it's
possible to add or subtract $360↑\circ$ without changing the meaning,
the answers $-330↑\circ$, $-300↑\circ$, $-150↑\circ$, and $-120↑\circ$
are also correct.

\exercise What are the coordinates of $z↓{1l}$ and $z↓{1r}$ after the
command `$\penpos1(10,-90)$', if $z↓1=(25,25)$?
\answer $z↓{1l}=(25,30)$, $z↓{1r}=(25,20)$.

\endgroup % end of the diminished \hsize
\danger The statement `$\penpos k(b,d)$' is simply an abbreviation for
two equations, `$z↓k={1\over2}[z↓{kl},z↓{kr}]$' and
`$z↓{kr}=z↓{kl}+(b,0)$ ↑{rotated}~$d\,$'. You might want to use other
equations to define the relationship between $z↓{kl}$, $z↓k$, and
$z↓{kr}$, instead of giving a "penpos" command, if an alternative
formulation turns out to be more convenient.

After `"penpos"' has specified the relation between three points, we still
don't know exactly where they are; we only know their positions relative
to each other. Another equation or two is needed in order to fix the
horizontal and vertical locations of each triple. For example, the three
"penpos" commands that led to the pen stroke on the previous page were
accompanied by the equations
\begindisplay
$z↓1=(0,2"pt")$;&$z↓2=(4"pt",0)$;&$x↓3=9"pt"$;&$y↓{3l}=y↓{2r}$;
\enddisplay
these made the information complete. There should be one $x$~equation and
one $y$~equation for each position; or you can use a $z$~equation, which
defines both $x$ and~$y$ simultaneously.

It's a nuisance to write long-winded @fill@ commands when broad-edge
pens are being simulated in this way, so \MF\ provides a convenient
abbreviation: You can write simply
\begindisplay
↑@penstroke@ $z↓{1e}\to z↓{2e}\{"right"\}\to\{"right"\}z↓{3e}$
\enddisplay
instead of the command `\thinspace@fill@ $z↓{1l}\to
z↓{2l}\{"right"\}\to\{"right"\}\,z↓{3l} \dashto
z↓{3r}\{"left"\}\to\{"left"\}\,z↓{2r}\to z↓{1r}\dashto\cycle$' that was
stated earlier. The letter `$e$' ↑↑"e" stands for the pen's edge. A @penstroke@
command fills the region `$p.l\dashto \reverse p.r\dashto\cycle$', where
$p.l$ and~$p.r$ are the left and right paths formed by changing each~`$e$'
into `$l$' or~`$r$', respectively.

\danger The @penstroke@ abbreviation can be used to draw cyclic paths
as well as ordinary ones. For example, the circle in exercise \circlex\
was created by saying simply `@penstroke@ $z↓{1e}\to z↓{2e}\to z↓{3e}\to
z↓{4e}\to\cycle$'. This type of penstroke essentially expands into
\begindisplay
@fill@ $z↓{1r}\to z↓{2r}\to z↓{3r}\to z↓{4r}\to\cycle$;\cr
@unfill@ $z↓{1l}\to z↓{2l}\to z↓{3l}\to z↓{4l}\to\cycle$;\cr
\enddisplay
or the operations `@fill@' and `@unfill@' are reversed, if points
$(z↓{1r},z↓{2r}, z↓{3r},z↓{4r})$ are on the inside and
$(z↓{1l},z↓{2l},z↓{3l},z↓{4l})$ are on the outside.

\dangerexercise The circle of exercise \circlex\ was actually drawn with
a slightly more complicated @penstroke@ command than just claimed: The
edges of the curve were forced to be vertical at
positions 1 and~3, horizontal at 2 and~4. How did the author do this?
\answer He said `@penstroke@
$z↓{1e}\{"up"\}\to z↓{2e}\{"left"\}\to z↓{3e}\{"down"\}
 \to z↓{4e}\{"right"\}\to\cycle$'.

\setbox0=\vtop{\kern 21pt
  \rightline{\vbox{\hbox to 216\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern6pt
      \figbox{4j}{216\apspix}{252\apspix}\vbox
      \kern-3pt
      \hbox to 216\apspix{\hidecoords(0,0)\hfil\hidecoords(w,0)}}\qquad}}
\dp0=0pt

\hangindent-147pt \hangafter2
\indent\strut\vadjust{\box0}%
Now let's design another letter ↑{T}, based on this new sort of pen, in order
to get further experience. The enlarged character shown here has seven key
positions, so we'll be specifying a total of $3\times7=21$ points.
Some nomenclature will be helpful:
The top of a~T is called the {\sl↑{bar}},
and the other stroke is called the {\sl↑{stem}}.

\hangindent-147pt
\hangafter\prevgraf \advance\hangafter by -16 % 2+14 (14 lines for the figure)
As before, we shall assume that two variables $h$ and~$w$ have been set up
to give the height and width of the character, in pixels. We shall also
assume that two other parameters are available: "thin", which tells
the breadth of the pen in the bar, and "thick", which governs the
breadth in the stem. Once we have a suitable program written we can
try different possibilities for "thin" and "thick" until we find what
goes best with other letters.

Since the program is somewhat technical, it should be skimmed on first reading.
It begins with "penpos" statements for the bar stroke; these are easy:
\begindisplay
$\penpos1("thin",70)$;\cr
$\penpos2("thin",35)$;\cr
$\penpos4("thin",35)$;\cr
$\penpos5("thin",55)$.\cr
\enddisplay
The next job is to place positions 1, 2, 4, and 5 on the raster by giving four
$x$~equations and four $y$~equations:
\begindisplay
$x↓1=0$; \ $x↓{2l}={1\over3}[x↓{1l},x↓{5l}]$;
\ $x↓{4l}={2\over3}[x↓{1l},x↓{5l}]$; \ $x↓5=w$;\cr
$y↓{1r}=h$; \ $y↓{2r}=y↓{4r}=.2[y↓{1r},y↓1]$; \ $y↓{5l}=.3[y↓{1l},y↓1]$.\cr
\enddisplay
By setting $x↓1=0$ and $y↓{1r}=h$, we define position 1 in such a way
that the middle point $z↓1$ occurs at the left edge of the type and the
right point $z↓{1r}$ occurs at the top edge. Positions 2 and~4 are
determined by placing the $x$~coordinates of their left points $z↓{2l}$
and~$z↓{4l}$ equally distant from $z↓{1l}$ and~$z↓{5l}$; the right points
$z↓{2r}$ and~$z↓{4r}$ are made to be a teeny bit lower than $z↓{1r}$. The
equation `$y↓{5l}=.3[y↓{1l},y↓1]$' puts the bottom of the bar slightly
higher at position~5 than at position~1. With these equations in addition
to the "penpos" specifications, \MF\ has enough information to determine
all of the coordinates $x↓{1l}$, $x↓1$, $x↓{1r}$, $x↓{2l}$, $x↓2$,
$x↓{2r}$, $x↓{4l}$, $x↓4$, $x↓{4r}$, $x↓{5l}$, $x↓5$, $x↓{5r}$, $y↓{1l}$,
$y↓1$, $y↓{1r}$, $y↓{2l}$, $y↓2$, $y↓{2r}$, $y↓{4l}$, $y↓4$, $y↓{4r}$,
$y↓{5l}$, $y↓5$, and~$y↓{5r}$.

A similar approach sets up the stem stroke. We want the thick pen to fall
inside the bar at position~3, so we set the angle to zero. A special
construction that we haven't seen before is used to make the pen taper
inward slightly at position~6:
\begindisplay
$\penpos6("thick",20)$; \ $\pentaper6(.1,0)$;\cr
$\penpos3(x↓{6r}-x↓{6l},0)$; \ $\penpos7("thick",10)$;\cr
$x↓3=.5w$; \ $x↓{6r}=x↓{3r}$; \ $x↓7=x↓6$; \
 $y↓3=y↓2$; \ $y↓6={2\over3}h$; \ $y↓7=0$.\cr
\enddisplay
The statement `$\pentaper6(.1,0)$' moves point $z↓{6l}$ to the right,
↑↑"pentaper" ↑↑{tapering}
one-tenth of the way towards $z↓6$ from where it was before tapering;
this makes the pen slightly thinner than "thick" at position~6. Point~$z↓6$
doesn't move, so it is no longer midway between $z↓{6l}$ and $z↓{6r}$
after the "pentaper" command has taken effect. However, point~$z↓7$ is
midway between $z↓{7l}$ and~$z↓{7r}$; since $z↓7$~is directly below~$z↓6$,
the stroke flares out slightly more to the left than to the right at
the base of the stem.

%It's possible, of course, to play with these equations and get different
%images by varying the angles, amounts of taper, and so on.

Finally the strokes are drawn by saying ↑↑"infinity" ↑↑{curl}
\begindisplay
@penstroke@ $z↓{1e}\{\curl\,"infinity"\}\to
	z↓{2e}\to z↓{4e}\to\{\curl\,"infinity"\}z↓{5e}$;\cr
@penstroke@ $z↓{3e}\to z↓{6e}\{"down"\}\to z↓{7e}$.\cr
\enddisplay
That's all it takes to make instant `{\manual\IOT}'.

\danger In general, the phrase `$\pentaper k(a,b)$' is shorthand for four
assignment statements, `$x↓{kl}:=a[x↓{kl},x↓k]$; $y↓{kl}:=a[y↓{kl},y↓k]$;
$x↓{kr}:=b[x↓{kr},x↓k]$; $y↓{kr}:=b[y↓{kr},y↓k]$'. Equations can usually
be given in any order, but `$:=$' ↑↑{:=} changes the meaning of values;
hence the ordering of statements can be significant when tapering is used.
For example, if the statement `$\penpos3(x↓{6r}-x↓{6l},0)$' had been given
before `$\pentaper6(.1,0)$', instead of after~it, the width of the pen at
position~3 would have been set equal to the value of $x↓{6r}-x↓{6l}$ {\sl
before\/} tapering, so the final width at position~3 would have been
greater than the final value of~$x↓{6r}-x↓{6l}$. We shall study the
differences between `$:=$' and~`$=$' in Chapter~10.

\danger It is important to note that these simulated pens
have a serious limitation compared to the way a real calligrapher's pen
works: The left and right edges of a "penpos"-made pen must never cross,
hence it is necessary to turn the pen when going around a curve.
Consider, for example the following two curves:
\displayfig 4k (6pc)
The left-hand circle was drawn with a broad-edge pen of fixed breadth,
held at a fixed angle; consequently the left edge of the pen was responsible
for the outer boundary on the left, but the inner boundary on the right.
\ (This curve was produced by saying `\pickup @pencircle@ xscaled~0.8"pt"
rotated~25; @draw@ $z↓1\to z↓2\to\cycle$'.) \ The right-hand shape
was produced by `$\penpos1(0.8"pt",25)$; $\penpos2(0.8"pt",25)$;
@penstroke@ $z↓{1e}\to z↓{2e}\to\cycle$'; important chunks of the shape
are missing at the crossover points, because they don't lie on either of
the circles $z↓{1l}\to z↓{2l}\to\cycle$ or $z↓{1r}\to z↓{2r}\to\cycle$.

\danger To conclude this chapter we shall improve the ↑{hex} character
{\manual\hexb} of Chapter~2, which is too dark in the middle because it has
been drawn with a pen of uniform thickness. The main trouble with unvarying
pens is that they tend to produce black blotches where two strokes meet,
unless the pens are comparatively thin or unless the strokes are nearly
perpendicular. We want to thin out the lines at the center just enough
to cure the darkness problem, without destroying the illusion that the lines
still seem (at first glance) to have uniform thickness.

\setbox0=\vtop{\kern 80pt
  \rightline{\vbox{\hbox to 200\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern3pt
      \figbox{4l}{200\apspix}{100\apspix}\vbox
      \kern-3pt
      \hbox to 200\apspix{\hidecoords(0,0)\hfil\hidecoords(w,0)}}\qquad}}
\dp0=0pt

\danger \strut\vadjust{\box0}%
It isn't difficult to produce `\thinspace
{\manual\hexe\hexe\hexe\hexe\hexe\hexe\hexe\hexe\hexe\hexe}\thinspace'
instead of `\thinspace
{\manual\hexb\hexb\hexb\hexb\hexb\hexb\hexb\hexb\hexb\hexb}\thinspace'
when we work with dynamically varying pens as follows:
\begindisplay
\pickup @pencircle@ scaled $b$;\cr
$"top"\,z↓1=(0,h)$; \ $"top"\,z↓2=(.5w,h)$; \ $"top"\,z↓3=(w,h)$;\cr
$"bot"\,z↓4=(0,0)$; \ $"bot"\,z↓5=(.5w,0)$; \ $"bot"\,z↓6=(w,0)$;\cr
$z↓{1'}=.25[z↓1,z↓6]$; $z↓{6'}=.75[z↓1,z↓6]$;\cr
$"theta"↓1:=\angle(z↓6-z↓1)+90$;\cr
$z↓{3'}=.25[z↓3,z↓4]$; $z↓{4'}=.75[z↓3,z↓4]$;\cr
$"theta"↓3:=\angle(z↓4-z↓3)+90$;\cr
$z↓7=z↓8=.5[z↓1,z↓6]$;\cr
$\penpos{1'}(b,"theta"↓1)$; $\penpos{6'}(b,"theta"↓1)$;\cr
$\penpos7(.6b,"theta"↓1)$;\cr
$\penpos{3'}(b,"theta"↓3)$; $\penpos{4'}(b,"theta"↓3)$;\cr
$\penpos8(.6b,"theta"↓3)$;\cr
@draw@ $z↓1\to z↓{1'}$; @draw@ $z↓{6'}\to z↓6$;\cr
@penstroke@ $z↓{1'e}\{z↓{6'}-z↓{1'}\}\to z↓{7e}\to\{z↓{6'}-z↓{1'}\}z↓{6'e}$;\cr
@draw@ $z↓3\to z↓{3'}$; @draw@ $z↓{4'}\to z↓4$;\cr
@penstroke@ $z↓{3'e}\{z↓{4'}-z↓{3'}\}\to z↓{8e}\to\{z↓{4'}-z↓{3'}\}z↓{4'e}$;\cr
@draw@ $z↓2\to z↓5$.\cr
\enddisplay
Here $b$ is the diameter of the pen at the terminal points;
`↑{angle}' computes the direction angle of a given vector.
Adding $90↑\circ$ to a direction angle gives a ↑{perpendicular}
direction (see the definitions of $"theta"↓1$ and~$"theta"↓3$).
It isn't necessary to take anything off of the vertical stroke $z↓2\to z↓5$,
because the two diagonal strokes fill more than the width of the vertical
stroke at the point where they intersect.

\setbox0=\vtop{\kern -30pt
  \rightline{\vbox{\hbox to 200\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern6pt
      \figbox{4m}{200\apspix}{100\apspix}\vbox
      \kern0pt
      \hbox to 200\apspix{\hidecoords(0,0)\hfil\hidecoords(w,0)}}\quad}}
\dp0=0pt

\begingroup \decreasehsize 125pt
\dangerexercise \strut\vadjust{\box0}%
Modify the hex character so that its ends are cut
sharply and confined to the bounding box, as shown.
\answer We use angles ↑{perpendicular} to $(w,h)$ and $(w,-h)$ at the
diagonal endpoints:
\begindisplay
$x↓{1l}=x↓{4l}=0$;\cr
$x↓2=x↓5=.5w$;\cr
$x↓{3r}=x↓{6r}=w$;\cr
$y↓{1r}=y↓2=y↓{3l}=h$;\cr
$y↓{4r}=y↓5=y↓{6l}=0$;\cr
$z↓7=z↓8=.5[z↓1,z↓6]$;\cr
$z↓{1'}=.25[z↓1,z↓6]$; \ $z↓{6'}=.75[z↓1,z↓6]$;\cr
$theta↓1:=\angle(w,-h)+90$;\cr
$\penpos1(b,theta↓1)$; \ $\penpos6(b,theta↓1)$;\cr
$\penpos7(.6b,theta↓1)$;\cr
$\penpos{1'}(b,theta↓1)$; \ $\penpos{6'}(b,theta↓1)$;\cr
@penstroke@ $z↓{1e}\to z↓{1'e}\{z↓{6'}-z↓{1'}\}\to z↓{7e}\to
\{z↓{6'}-z↓{1'}\}z↓{6'e}\to z↓{6e}$;\cr
$z↓{3'}=.25[z↓3,z↓4]$; \ $z↓{4'}=.75[z↓3,z↓4]$;\cr
$theta↓3:=\angle(-w,-h)+90$;\cr
$\penpos3(b,theta↓3)$; \ $\penpos4(b,theta↓3)$;\cr
$\penpos8(.6b,theta↓3)$;\cr
$\penpos{3'}(b,theta↓3)$; \ $\penpos{4'}(b,theta↓3)$;\cr
@penstroke@ $z↓{3e}\to z↓{3'e}\{z↓{4'}-z↓{3'}\}\to z↓{8e}\to
\{z↓{4'}-z↓{3'}\}z↓{4'e}\to z↓{4e}$;\cr
$\penpos2(b,0)$; \ $\penpos5(b,0)$; \ @penstroke@ $z↓{2e}\to z↓{5e}$.\cr
\enddisplay

\endgroup % end of the diminished \hsize

\endchapter

It is very important that the nib be cut ``sharp,''
and as often as its edge wears blunt it must be resharpened.
It is impossible to make ``clean cut'' strokes with a blunt pen.
\author EDWARD ↑{JOHNSTON}, {\sl Writing \& Illuminating, %
 \& Lettering\/} (1906)

\bigskip

I might compare the high-speed computing machine
to a remarkably large and awkward pencil
which takes a long time to sharpen and
cannot be held in the fingers in the usual manner so that it
gives the illusion of responding to my thoughts,
but is fitted with a rather delicate engine
and will write like a mad thing
provided I am willing to let it dictate pretty much
the subjects on which it writes.
\author R. H. ↑{BRUCK}, {\sl Computational Aspects of Certain
  Combinatorial Problems\/} (1956) % AMS Symp Appl Math 6, p31

\eject
\beginchapter Chapter 5. Running\\\MF

It's high time now for you to stop reading and to start playing with the
computer, since \MF\ is an interactive system that is best learned by
trial and error. \ (In fact, one of the nicest things about computer graphics
is that errors are often more interesting and more fun than ``successes.'')

You probably will have to ask somebody how to deal with the idiosyncrasies
of your particular version of the system, even though \MF\ itself works in
essentially the same way on all machines; different computer terminals and
different hardcopy devices make it necessary to have somewhat different
interfaces. In~this chapter we shall assume that you have a computer
terminal with a reasonably high-resolution graphics display; that you have
access to a (possibly low-resolution) output device; and that you can
rather easily get that device to work with newly created fonts.

OK, are you ready to run the program? First you need to log in, of course;
then start \MF, which is usually called ↑|mf| for short. Once you've figured
out how to do it, you'll be welcomed by a message something like
$$\def\\{{\rm\ }} % take a wee bit off of the \tt spaces
\vtop{\line{\indent \tt
This\\is\\METAFONT,\\Version\\1.0\\(preloaded\\base=plain 84.11.8)}
\leftline{\indent \tt **}}$$
The `↑|**|' is \MF's way of asking you for an input file name.
% Incidentally, 84.11.8 was Hermann's 66th birthday.

Now type `|\relax|'---that's ↑{backslash}, |r|, |e|, |l|, |a|, |x|---and
hit ↑\<return> (or~whatever stands for ``end-of-line'' on your keyboard).
\MF\ is all geared up for action, ready to make a big font; but you're
saying that it's all right to take things easy, since this is going to
be a real simple run. The backslash means that \MF\ should not read a file,
it should get instructions from the keyboard; the `↑|relax|' means
``do nothing.''

The machine will respond by typing a single asterisk: `↑|*|'. This means
it's ready to accept instructions (not the name of a file). Type the
following, just for fun:
\begintt
drawdot (35,70); showit;
\endtt
and \<return>---don't forget to type the semicolons along with the other
stuff. A more-or-less circular dot should now appear on your screen! And
you should also be prompted with another asterisk.
Type
\begintt
drawdot (65,70); showit;
\endtt
and \<return>, to get another dot. \ (Henceforth we won't keep mentioning
the necessity of \<return>ing after each line of keyboard input.) \ Finally,
type
\begintt
draw (20,40)..(50,25)..(80,40); showit; shipit; end.
\endtt
This draws a curve through three given points, displays the result,
↑↑|showit| ↑↑|shipit| ↑↑|end|
ships it to an output file, and stops. \MF\ should respond with `|[0]|',
meaning that it has shipped out a character whose number is zero, in the
``font'' just made; and it should also tell you that it has created
an output file called `|mfput.gf|'. \ (The name ↑|mfput| is used when
you haven't specified any better name in response to the ↑|**| at the
beginning. The suffix ↑|gf| stands for ``↑{generic font}''; the data in
|mfput.gf| can be converted into fonts suitable for a
wide assortment of typographical output devices. Since it doesn't
match the font file conventions of any name-brand manufacturer,
we call it generic.)

This particular file |mfput.gf| won't make a very interesting font,
because it contains only one character, and because it probably doesn't
have the correct resolution for your output device. However, it does
have the right resolution for hardcopy proofs of characters; your next
step therefore should be to convert the data of |mfput.gf| into a
picture, suitable for framing. There should be a program called
↑|GFtoDVI| on your computer. Apply it to |mfput.gf|, thereby
obtaining a file called |mfput.dvi| ↑↑|dvi| that can be printed.
Your friendly local computer hackers will tell you how to run
|GFtoDVI| and how to print |mfput.dvi|; then you'll have a marvelous
souvenir of your very first encounter with \MF.

\smallskip
Once you have made a complete test run as just described, you will
know how to get through the whole cycle, so you'll be ready to tackle
a more complex project. Our next experiment will therefore be
to work from a file, instead of typing the input online.

Use your favorite text editor to create a file called |io.mf| that
contains the following 23 lines of text (no more, no less):
$$\halign{\hbox to\parindent{\hfil\sevenrm#\ \ }&#\hfil\cr
1&|mode_setup;|\cr\noalign{↑↑@mode\_setup@}
2&| em#:=10pt#; cap#:=7pt#;|\cr
3&| thin#:=1/3pt#; thick#:=5/6pt#;|\cr
4&| o#:=1/5pt#;|\cr
5&|define_pixels(em,cap);|\cr
6&|define_blacker_pixels(thin,thick);|\cr
7&|define_corrected_pixels(o);|\cr
8&| curve_sidebar=round 1/18em;|\cr
9&|beginchar("O",0.8em#,cap#,0); "The letter O";|\cr
10&| penpos1(thick,10); penpos2(.1[thin,thick],90-10);|\cr
11&| penpos3(thick,180+10); penpos4(thin,270-10);|\cr
12&| x1l=w-x3l=curve_sidebar; x2=x4=.5w;|\cr
13&| y1=.49h; y2l=-o; y3=.51h; y4l=h+o;|\cr
14&| penstroke z1e{down}..z2e{right}|\cr
15&|            ..z3e{up}..z4e{left}..cycle;|\cr
16&| penlabels(1,2,3,4); endchar;|\cr
17&|def test_I(expr code,trial_stem,trial_width) =|\cr
18&| stem#:=trial_stem*pt#; define_blacker_pixels(stem);|\cr
19&| beginchar(code,trial_width*em#,cap#,0); "The letter I";|\cr
20&|  penpos1(stem,15); penpos2(stem,12); penpos3(stem,10);|\cr
21&|  x1=x2=x3=.5w; y1=h; y2=.55h; y3=0;|\cr
22&|  pentaper2(.25,.1); penstroke z1e..z2e{down}..z3e;|\cr
23&|  penlabels(1,2,3); endchar; enddef;|\cr}$$
(But don't type the numbers at the left of these lines; they're
only for reference.)

This example file is dedicated to ↑{Io}, the Greek goddess of input
and output. It's a trifle long, but you'll be able to get worthwhile
experience by typing it; so go ahead and type it now. For your own
good. And think about what you're typing, as you go; the example
introduces several important features of \MF\ that you can learn
as you're creating the file.

Here's a brief explanation of what you've just typed: Line~1 contains a
command that usually appears near the beginning of every \MF\ file;
it tells the computer to get ready to work in whatever ``mode'' is
currently desired. \ (A file like |io.mf| can be used to generate
proofsheets as well as to make fonts for a variety of devices at a
variety of magnifications, and `@mode\_setup@' is what adapts \MF\
to the task at hand.) \ Lines 2--8 define parameters that will be used
to draw the letters in the font. Lines 9--16 give a complete program
for the letter `O'; and lines 17--23 give a program that will draw
the letter~`I' in a number of related ways.

It all looks pretty frightening at first glance, but a closer look
shows that Io is not so mysterious once we penetrate her disguise.
Let's spend a few minutes studying the file in more detail.

Lines 2--4 define dimensions that are independent of the mode; the `|#|'
↑↑{sharpsign} signs are meant to imply ``sharp'' or ``true'' ↑{units of
measure}, which remain the same whether we are making a font at high or
low resolution. For example, one `|pt#|' is a true printer's point, one
72.27th of an inch. This is quite different from the `↑"pt"' we have
discussed in previous chapters, because `"pt"' is the number of pixels
that happen to correspond to a printer's point when the current resolution
is taken into account. The value of `|pt#|' never changes, but
@mode\_setup@ establishes the appropriate value of `"pt"'.

The ↑{assignments} `|em#:=10pt#|' and `|cap#:=7pt#|' in line~2 mean that
the Io font has two parameters, called "em" and "cap", whose mode-independent
values are 10 and~7 points, respectively. The statement ↑↑@define\_pixels@
`|define_pixels(em,cap)|' on line~5 converts these values into pixel
units. For example, if we are working at the comparatively low resolution
of 3~pixels per~pt, the values of "em" and "cap" after the computer has
performed the instructions on line~5 will be $"em"=30$ and $"cap"=21$.
\ (We will see later that the widths of characters in this font are
expressed in terms of ems, and that "cap" is the height of the capital
letters. A change to line~2 will therefore affect the widths and/or heights
of all the letters.)

Similarly, the Io font has parameters called "thin" and "thick", defined
on line~3 and converted to pixel units in line~6. These are used to control
the breadth of a simulated pen when it draws the letter~O. Experience has
shown that \MF\ produces better results on certain output devices if
pixel-oriented pens are made slightly broader than the true dimensions would
imply, because black pixels sometimes tend to ``burn off'' in the process
of printing. The command on line~6, `|define_blacker_pixels|',
↑↑@define\_blacker\_pixels@ adds a correction based on the device for which
the font is being prepared. For example, if the resolution is 3~pixels
per point, the value of "thin" when converted from true units to pixels
by @define\_pixels@ would be~1, but @define\_blacker\_pixels@ might set
"thin" to a value closer to~2.

The `|o|' parameter ↑↑"o" on line 4 represents the amount by which curves will
↑{overshoot} their boundaries. This is converted to pixels in yet another
way on line~7, so as to avoid yet another problem that arises in low-resolution
printing. The author apologizes for letting such real-world considerations
intrude into a textbook example; let's not get bogged down in fussy details
now, since these refinements will be explained in Chapter~11 after we have
mastered the basics. For now, the important point is simply that a typeface
design usually involves parameters that represent physical lengths. The
true, ``sharped'' forms of these parameters need to be converted to
``unsharped'' pixel-oriented quantities, and best results are obtained when
such conversions are done carefully. After \MF\ has obeyed line~7 of the
example, the pixel-oriented parameters "em", "cap", "thin", "thick",
and~"o" are ready to be used as we draw letters of the font.

Line 8 defines a quantity called "curve\_sidebar" ↑↑{sidebar} that will
measure the distance of the left and right edges of the `O' from the
bounding box. It is computed by ↑{rounding} ${1\over18}"em"$ to the nearest
integer number of pixels. For example, if $"em"=30$ then ${30\over18}=
{5\over3}$ yields the rounded value $"curve\_sidebar"=2$; there will be
two all-white columns of pixels at the left and right of the `O',
when we work at this particular resolution.

Before we go any further, we ought to discuss the strange collection
of words and pseudo-words in the file |io.mf|. Which of the terms
`|mode_setup|', `|em|', `|curve_sidebar|' and so forth are part of
the \MF\ language, and which of them are made up specifically for
the Io example? Well, it turns out that almost {\sl nothing\/} in this
example is written in the pure \MF\ language that the computer understands!
\MF\ is really a low-level language that has been designed to allow easy
adaptation to many different styles of programming, and |io.mf|
illustrates just one of countless ways to use it. Most of the terms
in |io.mf| are conventions of ``↑{plain} \MF\!,'' which is a collection
of subroutines found in Appendix~B. \MF's primitive capabilities are
not meant to be used directly, because that would force a particular style
on all users. A ``base file'' is generally loaded into the computer
at the beginning of a run, so that a standard set of convention is
readily available. \MF's welcoming message, quoted at the
beginning of this chapter, says `|preloaded| |base=plain|'; it
means that the primitive \MF\ language has been extended to include the
features of the plain base file.  This book is not only about \MF; it also
explains how to use the conventions of \MF's plain base. Similarly, {\sl
The \TeX book\/} describes a standard extension of \TeX\ called ``plain
\TeX\ format''; ↑↑{TeX} the ``plain'' extensions of \TeX\ and \MF\ are
completely analogous to each other.

The notions of @mode\_setup@, @define\_pixels@, @beginchar@, "penpos",
and many other things found in |io.mf| are aspects
of plain \MF\ but they are not hardwired into \MF\ itself. Appendix~B
defines all of these things, as well as the relations between ``sharped''
and ``unsharped'' variables. Even the fact that $z↓1$ stands for
$(x↓1,y↓1)$ is defined in Appendix~B; \MF\ does not have this built~in.
You are free to define even fancier bases as you gain more experience,
but the plain base is a suitable starting point for a novice.

\danger If you have important applications that make use of a different
base file, it's possible to create a version of \MF\ that has any desired
base preloaded. Such a program is generally called by a special name,
since the nickname `↑|mf|' is reserved for the version that includes the
standard plain base assumed in this book. For example, the author has made
a special version called `↑|cmmf|' just for the ↑{Computer Modern} typefaces
he has been developing, so that the Computer Modern base file does not
have to be loaded each time he makes a new experiment.

\danger There's a simple way to change the base file from the one that has
been preloaded: If the first character you type in response to `↑|**|' is
an ↑{ampersand} (\thinspace`|&|'\thinspace), \MF\ will replace its memory
with a specified base file before proceeding. If, for example, there is a
base file called `|cm.base|' but not a special program called `|cmmf|',
you can substitute the Computer Modern base for the plain base in |mf| by
typing `|&cm|' at the very beginning of a run.  If you are working with a
program that doesn't have the plain base preloaded, the first experiment
in this chapter won't work as described, but you can do it by starting
with `|&plain \relax|' instead of just `|\relax|'.  These conventions are
exactly the same as those of \TeX.

Our Ionian example uses the following words that are not part of plain
\MF: "em", "cap", "thin", "thick", "o", "curve\_sidebar", "test\_I", "code",
"trial\_stem", "trial\_width", and "stem". If you change these to some other
words or symbols---for example, if you replace `|thin|' and `|thick|' by
`|t|' and `|T|' respectively, in lines 3, 6, 10, and~11---the results will
be unchanged, unless your substitutions just happen to clash with something
that plain \MF\ has already pre\"empted. In general, the best policy is to
choose descriptive terms for the quantities in your programs, since they
are not likely to conflict with reserved pseudo-words like "penpos" and
@endchar@.

We have already noted that lines 9--16 of the file represent a program
for the letter `O'. The main part of this program, in lines 10--15,
uses the ideas of Chapter~4, but we haven't seen the stuff in lines 9
and~16 before. Plain \MF\ makes it convenient to define letters by starting
each one with
\begindisplay
$@beginchar@($\<code>, \<width>, \<height>, \<depth>);↑↑@beginchar@
\enddisplay
here \<code> is either a quoted single character like |"O"| or a number that
represents the character's position in the final font. The other three
quantities \<width>, \<height>, and \<depth> say how big the ↑{bounding box}
is, so that typesetting systems like \TeX\ will be able to use the character.
These three dimensions must be given in device-independent units, i.e.,
in ``↑{sharped}'' form.

\exercise What are the height and width of the bounding box described
in the @beginchar@ command on line~9 of |io.mf|, given the parameter
values defined on line~2? Give your answer in terms of printer's points.
\answer The width is |0.8em#|, and an |em#| is 10 true points, so the
box will be exactly $8\pt$ wide in device-independent units. The
height will be $7\pt$. \ (And the depth below the baseline will be $0\pt$.)

Each @beginchar@ operation assigns values to special variables called
$w$, $h$, and~$d$, ↑↑"w" ↑↑"h" ↑↑"d" which represent the respective
width, height, and depth of the current character's bounding box,
↑{rounded} to the nearest integer number of pixels. Our example file
uses $w$ and~$h$ to help establish the locations of several pen positions
(see lines 12, 13, and~21 of |io.mf|).

\exercise Continuing the previous exercise, what will be the values of
$w$ and~$h$ if there are exactly 3.6 pixels per point?
\answer $8\times3.6=28.8$ rounds to the value $w=29$; similarly, $h=25$.
\ (And $d=0$.)

There's a quoted phrase |"The| |letter| |O"| at the end of line~9; this is
simply a title that will be used in printouts.

The `|endchar|' ↑↑@endchar@ on line 16 finishes the character that was
begun on line~9, by writing it to an output file and possibly displaying
it on your screen. We will want
to see the positions of the control points $z↓1$, $z↓2$,
$z↓3$, and~$z↓4$ that are used in its design, together with the auxiliary
points $(z↓{1l},z↓{2l},z↓{3l},z↓{4l})$ and $(z↓{1r},z↓{2r},z↓{3r},z↓{4r})$
that come with the "penpos" conventions; the statement `|penlabels(1,2,3,4)|'
↑↑"penlabels" takes care of labelling these points on the proofsheets.

So much for the letter O. Lines 17--23 are analogous to what we've seen
before, except that there's a new wrinkle: They contain a little program
↑↑@def@ enclosed by `|def...enddef|', which means that a
{\sl↑{subroutine}\/} is being defined.  In other words, those lines set up
a whole bunch of \MF\ commands that we will want to execute several times
with minor variations. The subroutine is called "test\_I" and it has three
parameters called "code", "trial\_stem", and "trial\_width" (see line~17).
The idea is that we'll want to draw several different versions of an `I',
having different stem widths and character widths; but we want to type the
program only once. Line~18 defines "stem"\0 and "stem", given a value of
"trial\_stem"; and lines 19--23 complete the program for the letter I.

\smallskip
Oops---we've been talking much too long about |io.mf|. It's time to stop
rambling and to begin Experiment~2 in earnest, because it will be much
more fun to see what the computer actually does with that file.

Are you brave enough to try Experiment 2? Sure.
Get \MF\ going again, but this time when the machine says `↑|**|' you should
say `|io|', since that's the name of the file you have prepared so
laboriously. \ (The file could also be specified by giving its full name
`|io.mf|', but \MF\ automatically adds `|.mf|' ↑↑|mf| ↑↑{file names} when
no suffix has been given explicitly.)

If all goes well, the computer should now flash its lights a bit
and---presto---a big `{\manual\IOO}' should be drawn on your screen.
But if your luck is as good as the author's, something will probably go wrong
the first time, most likely because of a typographic error in the file.
A \MF\ program contains lots of data with comparatively little redundancy,
so a single error can make a drastic change in the meaning. Check that
you've typed everything perfectly: Be sure to notice the difference between
the letter~`|l|' and the numeral~`|1|' (especially in line~12, where it
says `|x1l|', not `|x11| or~`|xll|'); be sure to distinguish between
the letter~`|O|' and the numeral~`|0|' (especially in line~9); be sure to
type the ``underline'' characters in words like `|mode_setup|'. We'll see
later that \MF\ can recover gracefully from most errors, but your job for
now is to make sure that you've got |io.mf| correct.

Once you have a working file, the computer will draw you an `{\manual\IOO}'
and it will also say something like this:
\begintt
(io.mf
The letter O [79])
*
\endtt
What does this mean? Well, `|(io.mf|' means that it has started to read your
file, and `|The| |letter|~|O|' was printed when the title was found in
line~9. Then when \MF\ got to the |endchar| on line~16, it said
`|[79]|' to tell you that it had just output character number~79.
\ (This is the ↑{ASCII} code for the letter~|O|; Appendix~C lists all
of these codes, if you need to know them.) The `|)|' after `|[79]|'
means that \MF\ subsequently finished reading the file, and the `↑|*|'
means that it wants another instruction.

Hmmm. The file contains programs for both I and O; why did we get only
an~O? Answer: Because lines 17--23 simply define the subroutine "test\_I";
they don't actually do anything with that subroutine. We need to activate
"test\_I" if we're going to see what it does. So let's type
\begintt
test_I("I",5/6,1/3);
\endtt
this invokes the subroutine, with $"code"=\null$|"I"|,
$"trial\_stem"={5\over6}$, and $"trial\_width"={1\over3}$. The computer will
now draw an~I corresponding to these values,\footnote*{Unless, of course,
there was a typing error in lines 17--23, where "test\_I" is defined.} and
it will prompt us for another command.

It's time to type `↑|end|' now, after which \MF\ should tell us that it has
completed this run and made an output file called `|io.gf|'. Running this
file through ↑|GFtoDVI| as in Experiment~1 will produce two proofsheets,
showing the `{\manual\IOO}' and the `{\manual\IOI}' we have created.
The output won't be shown here, but you can see the results by doing
the experiment personally.

Look at those proofsheets now, because they provide instructive examples
of the simulated broad-edge pen constructions introduced in Chapter~4.
Compare the `{\manual\IOO}' with the program that drew it: Notice that
the $\penpos2$ in line~10 makes the curve slightly thicker at the ↑↑"penpos"
bottom than at the top; that the equation `$x↓{1l}=w-x↓{3l}="curve\_sidebar"$'
in line~12 makes the right edge of the curve as far from the right of the
bounding box as the left edge is from the left; that line~13 places point~1
slightly lower than point~3. Line~22 includes a ↑"pentaper" command that moves
point $z↓{2l}$ inward, 25\%~closer than usual to point~$z↓2$, while
$z↓{2r}$ moves 10\%~closer.

\danger Your proof copy of the `{\manual\IOO}' should show twelve dots
for key points; but only ten of them will be labeled, because there isn't
room enough to put labels on points 2 and~4. The missing labels usually
appear in the upper right corner, where it might say, e.g.,
`|4|~|=|~|4l|~|+|~|(-1,-5.9)|'; this
means that point $z↓4$ is one pixel to the left and 5.9 pixels down
from point~$z↓{4l}$, which is labeled. \ (Some implementations omit this
information, because there isn't always room for it.)

The proofsheets obtained in Experiment~2 show the key points and the
bounding boxes, but this extra information can interfere with our
perception of the character shape itself. There's a simple way to
get proofs that allow a viewer to criticize the results from an aesthetic
rather than a logical standpoint; the creation of such proofs will be the
goal of our next experiment.

Here's how to do Experiment~3: Start \MF\ as usual, then type
\begintt
\mode=smoke; input io
\endtt
in response to the `↑|**|'. This will input file |io.mf| again,
after establishing ``smoke'' mode. \ (As in Experiment~1, the command line
begins with `|\|' so that the computer knows you aren't starting with
the name of a file.) \ Then complete the run exactly ↑↑{backslash}
as in Experiment~2, by typing `|test_I("I",5/6,1/3);| |end|';
and apply |GFtoDVI| to the resulting file |io.gf|.

This time the proofsheets will contain the same characters as before, but
they will be darker and without labelled points. The bounding boxes will
be indicated only by small markings at the corners; you can put these
boxes next to each other and tack the results up on the wall, then stand
back to see how the characters will look when set by a high-resolution
typesetter. \ (This way of working is called ↑"smoke" mode because it's
analogous to the ``smoke proofs'' that punch-cutters traditionally used to
test their handiwork. They held the newly cut type over a candle flame so
that it would be covered with carbon, then they pressed it on paper to
make a clean impression of the character, in order to see whether changes
were needed.)

\danger Incidentally, many systems allow you to invoke \MF\ by typing
a one-line command like `|mf|~|io|' in the case of Experiment~2; you
don't have to wait for the `|**|' before giving a file name. Similarly,
the one-liners `|mf|~|\relax|' and `|mf|~|\mode=smoke;| |input|~|io|' can be
used on many systems at the beginning of Experiments 1 and~3. You might want
to try this, to see if it works on your computer; or you might ask
somebody if there's a similar shortcut.

Experiments 1, 2, and 3 have demonstrated how to make proof drawings of
test characters, but they don't actually produce new fonts that can be
used in typesetting. For this, we move onward to Experiment~4, in which
we put ourselves in the position of a person who is just starting to
design a new typeface. Let's imagine that we're happy with the~O of
|io.mf|, and that we want a ``sans serif'' I in the general style produced
by "test\_I", but we aren't sure about how thick the stem of the~I
should be in order to make it blend properly with the~O. Moreover, we aren't
sure how much white space to leave at the sides of the~I. So we want to do
some typesetting experiments, using a sequence of different I's.

The ideal way to do this would be to produce a high-resolution test font and to
view the output at its true size. But this may be too expensive, because fine
printing equipment is usually available only for large production runs.
The next-best alternative is to use a low-resolution printer but to magnify
the output, so that the resolution is effectively increased. We shall adopt
the latter strategy, because it gives us a chance to learn about ↑{magnification}
as well as fontmaking.

After starting \MF\ again, you can begin Experiment 4 by typing
\begintt
\mode=localfont; mag=4; input io
\endtt
in response to the `|**|'. The ↑{plain base} at your installation is supposed
to recognize ↑|localfont| as the name of the mode that makes fonts for your
``standard'' output device. The equation `|mag=4|' means that this run will
produce a font that is magnified fourfold; i.e., the results will be
4~times bigger than usual.

The computer will read |io.mf| as before, but this time it won't display an~`O';
characters are normally not displayed in fontmaking modes, because we usually
want the computer to run as fast as possible when it's generating a font
that has already been designed. All you'll see is `|(io.mf| |[79])|',
followed by~`↑|*|'. Now the fun starts: You should type
\begintt
code=100;
for s=7 upto 10:
 for w=5 upto 8:
  test_I(incr code,s/10,w/20);
endfor endfor end.
\endtt
(Here `↑|upto|' must be typed as a single word.) \ We'll learn about
repeating things with `↑|for||...|↑|endfor|' in Chapter~19. This little
program produces 16 versions of the letter~I, with stem widths of
$7\over10$, $8\over10$, $9\over10$, and~${10\over10}\pt$, and with
character widths of $5\over20$, $6\over20$, $7\over20$, and~${8\over20}\,
\rm em$. The sixteen trial characters will appear in positions 101 through~116
of the font; it turns out that these are the ↑{ASCII} codes for lower case
letters |e| through~|t| inclusive. \ (Other codes would have been used if
`|code|' had been started at a value different from~100. The instruction
`|incr|~|code|' increases the value of |code| by~1 and produces the new value;
thus, each use of |test_I| has a different code number.) ↑↑"incr"

This run of \MF\ will not only produce a generic font |io.gf|, it will also
create a file called |io.tfm|, the ``↑{font metric file}'' that tells
↑↑{output of METAFONT} ↑↑|tfm|
typesetting systems like \TeX\ how to make use of the new font. The remaining
part of Experiment~4 will be to put \TeX\ to work: We shall make some test
patterns from the new font, in order to determine which `I' is best.

You may need to ask a local system wizard for help at this point, because
it may be necessary to move the file |io.tfm| to some special place where
\TeX\ and the other typesetting software can find it. Furthermore, you'll
need to run a program that converts |io.gf| to the font format used by your
local output device. But with luck, these will both be fairly simple
operations, and a new font called `|io|' will effectively be installed
on your system. This font will contain seventeen letters, namely an |O| and
sixteen |I|'s, where the |I|'s happen to be in the positions normally occupied
by |e|, |f|, \dots,~|t|. Furthermore, the font will be magnified fourfold.

You can use \TeX\ to typeset from this font like any other, but for the
purposes of Experiment~4 it's best to use a special \TeX\ package that has
been specifically designed for font testing. All you need to do is to
run \TeX---which is just like running \MF, except that you call it `|tex|'
instead of `|mf|'; and you simply type `↑|testfont|' in reply to \TeX's
`|**|'.  \ (The |testfont| routine should be available on your system; if
not, you or somebody else can type it in, by copying the relevant material
from Appendix~H\null.) \ You will then be asked for the name of the font
you wish to test. Type
\begintt
io scaled 4000
\endtt
(which means the |io| font magnified by 4, in \TeX's jargon),
since this is what \MF\ just created. The machine will now ask you for
a test command, and you should reply
\begintt
\mixture
\endtt
to get the ``↑{mixture}'' test. \ (Don't forget the ↑{backslash}.) \
You'll be asked for a ↑{background letter}, a starting letter, and an
ending letter; type `|O|', `|e|', and `|t|', respectively. This will
produce sixteen lines of typeset output, in which the first line contains
a mixture of |O| with~|e|, the second contains a mixture of |O|~with~|f|,
and so on.  To complete Experiment~4, type `|\end|' to \TeX, and print the
file |testfont.dvi| ↑↑|dvi| that \TeX\ gives you.

\setbox0=\hbox{\kern.5pt I\kern.5pt} \def\\{\copy0}
If all goes well, you'll have sixteen lines that say `O\\OO\\\\OOO\\\\\\O\\',
but with a different I on each line. In order to choose the line that looks
best, without being influenced by neighboring lines, it's convenient to take
two sheets of blank paper and use them to mask out all of the lines
except the one you're studying. Caution: These letters are four times
larger than the size at which the final font is meant to be viewed,
so you should look at the samples from afar. Xerographic reductions may
introduce distortions that will give misleading results. Sometimes when
you stare at things like this too closely, they all look wrong, or
they all look right; first impressions are usually more significant
than the results of logical reflection. At any rate, you should be able
to come up with an informed judgment about what values to use for the
stem width and the character width of a decent `I'; these can then be
incorporated into the program, the `|def|' and `|enddef|' parts of
|io.mf| can be removed, and you can go on to design other characters
that go with your I and~O. Furthermore you can always go back and make
editorial changes after you see your letters in more contexts.

\dangerexercise Once you have a satisfactory `{\manual\IOI}' and
`{\manual\IOO}', add a letter `\thinspace{\manual\IOT}\thinspace' by
adapting the example at the end of Chapter~4. \ [{\sl Hint:\/} The width
should be $0.6\,$em.]
\answer It's merely necessary to supply the proper environment
by using @beginchar@, etc., and by defining the appropriate
stem widths. We shouldn't use the names "thin" and "thick", which appear
already in the program for~O, unless we want to adopt exactly the same
conventions in the~T. The following solution assumes that the
``winning'' stem width for~I is $0.9\pt$:
\begintt
bar#:=.8pt#; stem#:=.9pt#;
define_blacker_pixels(bar,stem);
beginchar("T",0.6em#,cap#,0); "The letter T";
penpos1(bar,70);
penpos2(bar,35);
penpos4(bar,35);
penpos5(bar,55);
x1=0; x2l=1/3[x1l,x5l]; x4l=2/3[x1l,x5l]; x5=w;
y1r=h; y2r=y4r=.2[y1r,y1]; y5l=.3[y1l,y1];
penpos6(stem,20); pentaper6(.1,0);
penpos3(x6r-x6l,0);
penpos7(stem,10);
x3=.5w; x6r=x3r; x7=x6;
y3=y2; y6=2/3h; y7=0;
penstroke z1e{curl infinity}..z2e..z4e..{curl infinity}z5e;
penstroke z3e..z6e{down}..z7e;
penlabels(1,2,3,4,5,6,7); endchar;
\endtt

\ddangerexercise The goddess Io was known in Egypt as ↑{Isis}.
Design an `{\manual\IOS}' for her.
\answer Here's one way, using variables like "thick" and "bar"
that have already been defined in the~O or in the~T of the ↑↑{S}
\rightfig A5a ({200\apspix} x 252\apspix) ↑-60pt
previous exercise:
\begintt
beginchar("S",5/9em#,cap#,0); "The letter S";
penpos1(bar,70); penpos2(bar,80);
penpos3(.5[bar,thick],200); penpos5(.5[bar,thick],210);
penpos6(bar,80); penpos7(.25[bar,thick],75);
pentaper2(.4,.6); pentaper6(.3,.5);
x1=x5; y1r=.94h+o;
x2=x4=x6=.5w; y2r=h+o; y4=.54h; y6l=-o;
x3r=.04em; y3=.5[y4,y2];
x5l=w-.03em; y5=.5[y4,y6];
.5[x7l,x7]=.04em; y7l=.1h-o;
path trial; trial=z3{down}..z4..{down}z5;
pair dz; dz=direction 1 of trial;
penpos4(thick,angle dz-90);
penstroke z1e..z2e{left}..z3e{down}
    ..z4e{dz}..z5e{down}..z6e{left}..z7e;
penlabels(1,2,3,4,5,6,7); endchar;
\endtt
Notice that the pen angle at point 4 has been found by letting \MF\
↑↑{direction} construct a ↑{trial path} through the center points,
then using the ↑{perpendicular} direction. The letters work reasonably
well at their true size: `{\manual\IOI\IOO} {\manual\IOI\IOS}
{\manual\IOI\IOS\IOI\IOS} {\manual\IOT\IOO\IOO}; {\manual\IOT\IOO\IOS\IOS}
{\manual\IOI\IOT}, {\manual\IOO\IOT\IOI\IOS}.'

Well, this isn't a book about type design; the example of |io.mf| is
simply intended to illustrate how a type designer might want to operate,
and to provide a run-through of the complete process from design of
type to its use in a document. We must go back now to the world of
computerese, and study a few more practical details about the use of \MF.

This has been a long chapter, but take heart: There's only one more
experiment to do, and then you will know enough about \MF\ to run it
fearlessly by yourself forever after. The only thing you are still missing
is some information about how to cope with error messages; sometimes
\MF\ stops and asks you what to do next. Indeed, this may have already
happened, and you may have panicked.

Error messages can be terrifying when you aren't prepared for them;
but they can be fun when you have the right attitude. Just remember that
you really haven't hurt the computer's feelings, and that nobody will
hold the errors against you. Then you'll find that running \MF\ might
actually be a creative experience instead of something to dread.

The first step in Experiment 5 is to plant some intentional mistakes
in the input file. Make a copy of |io.mf| and call it |badio.mf|; then
change line~1 of |badio.mf| to
\begintt
mode setup; % an intentional error!
\endtt
(thereby omitting the underline character in |mode_setup|).
Also change the first semicolon (\thinspace`|;|'\thinspace) on line~2
to a colon (\thinspace`|:|'\thinspace);
change `|thick,10|' to `|thick,l0|' on line~10 (i.e., replace the numeral~`|1|'
by the letter~`|l|'\thinspace); and change `|thin|' to `|thinn|' on line~11.
These four changes introduce typical typographic errors, and it will be
instructive to see if they lead to any disastrous consequences.

Now start \MF\ up again; but instead of cooperating with the computer, type
`|mumble|' in reply to the~`|**|'. \ (As long as you're going to make
intentional mistakes, you might as well make some dillies.) \
\MF\ will say that it can't find any file called |mumble.mf|,
and it will ask you for another name. Just hit \<return> this time;
you'll see that you had better give the name of a real file.
So type `|badio|' and wait for \MF\ to find one of the {\sl faux pas\/}
in that messed-up text.

Ah yes, the machine will soon stop, after typing something like this:
\begintt
>> mode.setup
! Isolated expression.
<to be read again> 
                   ;
l.1 mode setup;
                % an intentional error!
?
\endtt
\MF\ begins its error messages with `|!|', and it sometimes precedes them
with one or two related mathematical expressions that are displayed on
lines starting with `↑|>>|'.  Each error message is also followed by lines
of context that show what the computer was reading at the time of the
error. Such context lines occur in pairs; the top line of the pair (e.g.,
`|mode| |setup;|'\thinspace) shows what \MF\ has looked at so far, and
where it came from (`|l.1|', i.e., line number~1); the bottom line (here
`|%|~|an| |intentional| |error!|'\thinspace) shows what \MF\ has yet to
read. In this case there are two pairs of context lines; the top pair
refers to a semicolon that \MF\ has read once but will be reading again,
because it didn't belong with the preceding material.

You don't have to take out pencil and paper in order to write down the
error messages that you get before they disappear from view, since \MF\
always writes a ``↑{transcript}'' or ``↑{log file}'' that records what
happened during each session. For example, you should now have a file
called |io.log| containing the transcript of Experiment~4, as well as a file
|mfput.log| that contains the transcript of Experiment~1. \ (The old
transcript of Experiment~2 was probably overwritten when you did
Experiment~3, and again when you did Experiment~4, because all three
transcripts were called |io.log|.) \ At the end of Experiment~5 you'll
have a file |badio.log| that will serve as a helpful reminder of
what errors need to be fixed up.

The `↑|?|' that appears after the context display means that \MF\ wants
advice about what to do next. If you've never seen an error message before,
or if you've forgotten what sort of response is expected, you can type
`|?|' now (go ahead and try it!); \MF\ will respond as follows:
\begintt
Type <return> to proceed, S to scroll future error messages,
R to run without stopping, Q to run quietly,
I to insert something, E to edit your file,
1 or ... or 9 to ignore the next 1 to 9 tokens of input,
H for help, X to quit.
\endtt
This is your menu of options. You may choose to continue in various ways:

\smallskip\item{1.}
Simply type \<return>. \MF\ will resume its processing, after
attempting to recover from the error as best it can.

\smallbreak\item{2.} Type `|S|'. \MF\ will proceed without
pausing for instructions if further errors arise. Subsequent error messages
will flash by on your terminal, possibly faster than you can read them, and
they will appear in your log file where you can scrutinize them at your
leisure. Thus, `|S|'~is sort of like typing \<return> to every message.

\smallbreak\item{3.} Type `|R|'. This is like `|S|' but even stronger,
since it tells \MF\ not to stop for any reason, not even if a file name
can't be found.

\smallbreak\item{4.} Type `|Q|'. This is like `|R|' but even more so,
since it tells \MF\ not only to proceed without stopping but also to
suppress all further output to your terminal. It is a fast, but somewhat
reckless, way to proceed (intended for running \MF\ with no operator in
attendance).

\smallbreak\item{5.} Type `|I|', followed by some text that you want to
insert. \MF\ will read this text before encountering what it
would ordinarily see ↑↑{inserting text online}
↑↑{online interaction, see interaction} ↑↑{interacting with MF}
next.

\smallbreak\item{6.} Type a small number (less than 100). \MF\ will
delete this many ↑{tokens} from whatever it is
about to read next, and it will pause again to give you another chance to
look things over.  ↑↑{deleting tokens}
\ (A~``token'' is a name, number, or symbol that \MF\ reads as a unit;
e.g., `|mode|' and `|setup|' and `|;|' are the first three tokens
of |badio.mf|, but `|mode_setup|' is the first token of |io.mf|.
Chapter~6 explains this concept precisely.)

\smallbreak\item{7.} Type `|H|'. This is what you should do now and whenever
you are faced with an error message that you haven't seen for a~while. \MF\
has two messages built in for each perceived error: a formal one and an
informal one. The formal message is printed first (e.g., `|!|~|Isolated|
|expression.|'\thinspace); the informal one is printed if you request
more help by typing `|H|', and it also appears in your log file if you
are scrolling error messages. The informal message tries to complement the
formal one by explaining what \MF\ thinks the trouble is, and often
by suggesting a strategy for recouping your losses.↑↑{help messages}

\smallbreak\item{8.} Type `|X|'. This stands for ``exit.'' It causes \MF\
to stop working on your job, after putting the finishing touches on your
|log| file and on any characters that have already been output to your |gf|
and/or |tfm| files.  The current (incomplete) character will not be output.

\smallbreak\item{9.} Type `|E|'. This is like `|X|', but it also prepares
the computer to edit the file that \MF\ is currently reading, at the
current position, so that you can conveniently make a change before
trying again.

\smallbreak\noindent
After you type `|H|' (or `|h|', which also works), you'll get a message
that tries to explain the current problem: The mathematical quantity just
read by \MF\ (i.e., |mode.setup|) was not followed by `|=|' or `|:=|', so
there was nothing for the computer to do with it. Chapter~6 explains that
a space between tokens (e.g., `|mode|~|setup|'\thinspace) is equivalent to
a period between tokens (e.g., `|mode.setup|'\thinspace).  The correct
spelling `|mode_setup|' would be recognized as a preloaded subroutine of
plain \MF\!, but plain \MF\ doesn't have any built-in meaning for
|mode.setup|. Hence |mode.setup| appears as a sort of orphan, and \MF\
realizes that something is amiss.

In this case it's OK to go ahead and type \<return>, because we really
don't need to do the operations of @mode\_setup@ when no special mode
has been selected. \MF\ will continue by forgetting the isolated expression,
and it will ignore the rest of line~1 because everything after a
↑↑{percent} `|%|'~sign is always ignored. \ (This is another thing that
will be explained in Chapter~6; it's a handy way to put ↑{comments}
into your \MF\ programs.) \ The changes that were made to line~1 of |badio.mf|
therefore have turned out to be relatively harmless. But \MF\ will
almost immediately encounter the mutilated semicolon in line~2:
\begintt
! Extra tokens will be flushed.
<to be read again> 
                   :
l.2  em#:=10pt#:
                 cap#:=7pt#;
?
\endtt
What does this mean? Type `|H|' to find out. \MF\ has no idea what to
do with a `|:|' at this place in the file, so it plans to recover by
``↑{flushing}'' or getting rid of everything it sees, until coming to a
semicolon.  It would be a bad idea to type \<return> now, since you'd lose
the important assignment `|cap#:=7pt#|', and that would lead to worse errors.

You might type `|X|' or `|E|' at this point, to exit from \MF\ and to fix
the errors in lines 1 and~2 before trying again. But it's usually best
to keep going, trying to detect and correct as many mistakes as possible
in each run, since that increases your productivity while
decreasing your computer bills. An experienced \MF\ user will quit
after an error only if the error is unfixable, or if there's almost no
chance that additional errors are present.

The solution in this case is to proceed in two steps: First type `|1|',
which tells \MF\ to delete the next token (the unwanted `|:|'); then type
`|I;|', which inserts a semicolon. This semicolon protects the rest of line~2
from being flushed away,
so all will go well until \MF\ reaches another garbled line.

The next error message is more elaborate, because it is detected while
\MF\ is trying to carry out a "penpos" command; "penpos" is not a
primitive operation (it is defined in plain \MF), hence a lot more
context is given:
\begintt
>> l0
! Improper transformation argument.
<to be read again> 
                   ;
penpos->...(EXPR3),0)rotated(EXPR4);
                                    z(SUFFIX2)=0.5[z(SUFF...
l.10  penpos1(thick,l0)
                       ; penpos2(.1[thin,thick],90-10);
?
\endtt
At first, such error messages will appear to be complete nonsense to you,
because much of what you see is low-level \MF\ code that you never wrote. But
you can overcome this hangup by getting a feeling for the way \MF\ operates.

The bottom line shows how much progress \MF\ has made so far in the |badio|
file:  It has read `|penpos1(thick,l0)|' but not yet the semicolon, on line~10.
The "penpos" routine expands into a long list of tokens; indeed, this list
is so long that it can't all be shown on two lines, and the appearances of
`↑|...|' indicate that the definition of "penpos" has been truncated here.
Parameter values are often inserted into the expansion of a high-level
routine; in this case, for example, `|(EXPR3)|' and `|(EXPR4)|' correspond
to the respective parameters `|thick|' and `|l0|', and `|(SUFFIX2)|'
corresponds to~`|1|'. ↑↑|EXPR| ↑↑|SUFFIX|
\MF\ detected an error just after encountering the phrase `|rotated(EXPR4)|';
the value of |(EXPR4)| was an undefined quantity (namely `|l0|',
which \MF\ treats as the subscripted variable~`$l↓0$'\thinspace), and
↑{rotation} is permitted only when a known numeric value has been supplied.
Rotations are particular instances of what \MF\ calls {\sl↑{transformations}\/};
hence \MF\ describes this particular error by saying that an ``improper
transformation argument'' was present.

When you get a multiline error message like this, the best clues about the
source of the trouble are usually on the bottom line (since that is what
you typed) and on the top line (since that is what triggered the error
message). Somewhere in there you can usually spot the problem.

If you type `|H|' now, you'll find that
\MF\ has simply decided to continue without doing the requested rotation.
Thus if you respond by typing \<return>, \MF\ will go on as if the program
had said `|penpos1(thick,0)|'. Comparatively little harm has been done;
but there's actually a way to fix the error perfectly before proceeding:
Insert the correct rotation by typing
\begintt
I rotated 10
\endtt
and \MF\ will rotate by 10 degrees as if `|l0|' had been `|10|'.

What happens next in Experiment 5? \MF\ will hiccup on the remaining
bug that we planted in the file. This time, however, the typo will
not be discovered until much later, because there's nothing wrong
with line~11 as it stands. \ (The variable |thinn| is not defined,
but undefined quantities are no problem unless you're doing something
complicated like rotation. Indeed, \MF\ programs typically
consist of equations in which there are lots of unknowns;
variables get more and more defined as time goes on. Hence spelling
errors cannot possibly be detected until the last minute.) \
Finally comes the moment of truth, when |badio| tries to draw a
path through an unknown point; and you will get an error message
that's even scarier than the previous one:
\begintt
>> 0.08682thinn+144
! Undefined x coordinate has been replaced by 0.
<to be read again> 
                   {
<for(l)> ...FFIX0){up}..z4(SUFFIX0){
                                    left}..cycle; ENDFOR
penstroke->...ath_.e:=(TEXT0);endfor
                                    .if.cycle.path_.l:cyc...
<to be read again> 
                   ;
l.15 ...      ..z3e{up}..z4e{left}..cycle;
|quad
?
\endtt
Wow; what's this?  The expansion of @penstroke@ involves a @for@ loop,
and the error was detected in the midst of it. The
expression `|0.08682thinn+144|' just above the error message implies that
the culprit in this case was a misspelled `|thin|'. If that hadn't been
enough information, you could have gleaned another clue from the fact that
`|z4(SUFFIX0)|' has just been read; |(SUFFIX0)| is the current loop value
and `|<for(l)>|' indicates that the value in question is `|l|', hence
$z↓{4l}$ is under suspicion. \ (Sure enough, the undefined $x$~coordinate
that provoked this error can be shown to be $x↓{4l}=0.08682"thinn"+144$.)

In any event the mistake on line~11 has propagated too far to be fixable,
so you're justified in typing `|X|' or~`|E|' at this point. But type~`|S|'
instead, just for fun: This tells \MF\ to plunge ahead, correcting all
remaining errors as best it can. \ (There will be a few more problems,
since several variables still depend on `|thinn|'.) \ \MF\ will draw a
very strange letter~O before it gets to the end of the file. Then you
should type `|end|' to terminate the run.

If you try to edit |badio.mf| again, you'll notice that line~2 still
contains ↑↑{editing} a colon instead of a semicolon; the fact that you
told \MF\ to delete the colon and to insert additional material doesn't
mean that your file has changed in any way. However, the transcript file
|badio.log| has a record of all the errors, so it's a handy reference when
you want to correct mistakes. \ (Why not look at
|badio.log| now, and |io.log| too, in order to get familiar with log files?)

\dangerexercise Suppose you were doing Experiment 3 with |badio| instead
of~|io|, so you began by saying `|\mode=smoke|; |input badio|'.  Then you
would want to recover from the error on line~1 by inserting a correct
@mode\_setup@ command, instead of by simply \<return>ing, because
@mode\_setup@ is what really establishes "smoke" mode. Unfortunately if you
try typing `|I|~|mode_setup|' in response to the ``isolated expression''
error, it doesn't work. What should you type instead?
\answer After an ``isolated expression,'' \MF\ thinks it is at the end of
a statement or command, so it expects to see a semicolon next. You should
type, e.g., `|I;|~|mode_setup|' to keep \MF\ happy.

By doing the five experiments in this chapter you have learned at first hand
(1)~how to produce proofsheets of various kinds, including ``smoke proofs'';
(2)~how to make a new font and test it; (3)~how to keep calm when \MF\
issues stern warnings. Congratulations! You're on the threshold of being able to
do lots more. As you read the following chapters, the best strategy
will be for you to continue making trial runs, using experiments
of your own design.

\exercise However, this has been an extremely long chapter,
so you should go outside now and get some {\sl real\/} exercise.
\answer Yes.

\endchapter

Let us learn how Io's frenzy came---
She telling her disasters manifold.
\author \AE SCHYLUS, ↑↑{Aeschylus} %
 {\sl Prometheus Bound\/} (c.\thinspace470 B.C.) % verse 801
 % This is the translation by Morshead

\bigskip

To the student who wishes to use graphical methods as a tool,
it can not be emphasized too strongly that practice in the use of that tool
is as essential as a knowledge of how to use it.
The oft-repeated pedagogical phrase, ``we learn by doing,'' is applicable here.
\author THEODORE ↑{RUNNING}, {\sl Graphical Mathematics\/} (1927) % p viii

\eject
\beginchapter Chapter 6. How \MF\\Reads What You\\Type

So far in this book we've seen lots of things that \MF\ can do, but we haven't
discussed what \MF\ can't do. We have looked at many examples of commands that
\MF\ can understand, but we haven't dwelt on the fact that the computer will
find many phrases unintelligible. It's time now to adopt a more systematic
approach and to study the exact rules of \MF's language. Then we'll know what
makes sense to the machine, and we'll also know how to avoid ungrammatical
utterances.

A \MF\ program consists of one or more lines of text, where each line is made
up of letters, numbers, punctuation marks, and other symbols that appear on
a standard computer keyboard. A total of 95 different characters can be
employed, namely a blank space plus the 94 visible symbols of standard ↑{ASCII}.
\ (Appendix~C describes the American Standard Code for Information
Interchange, popularly known as ``ASCII,'' under which code numbers 33
through~126 have been assigned to 94 specific symbols. This particular
coding scheme is not important to a \MF\ programmer; the only relevant thing
is that 94 different nonblank symbols can be used.)

\MF\ converts each line of text into a series of {\sl ↑{tokens}}, and a
programmer should understand exactly how this conversion takes place.
Tokens are the individual lexical units that govern the computer's
activities; they are the basic building blocks from which meaningful
sequences of instructions can be constructed. We discussed tokens briefly
at the end of the previous chapter; now we shall consider them in detail.
Line~9 of the file |io.mf| in that chapter is a typical example of what
the machine might encounter:
\begintt
beginchar("O",0.8em#,cap#,0); "The letter O";
\endtt
When \MF\ reads these ASCII characters it finds sixteen tokens:
\begindisplay \chardef\"=`\" \openup 2pt
\ttok{beginchar}\quad\ttok{(}\quad\ttok{\"O\"}\quad
 \ttok{,}\quad\ttok{0.8}\quad\ttok{em}\quad\ttok{\#}\quad\ttok{,}\cr
\ttok{cap}\quad\ttok{\#}\quad\ttok{,}\quad\ttok{0}\quad
 \ttok{)}\quad\ttok{;}\quad\ttok{\"The letter O\"}\quad\ttok{;}\cr
\enddisplay
Two of these, |"O"| and |"The| |letter| |O"|, are called {\sl↑{string tokens}\/}
because they represent strings of characters. Two of them, `|0.8|' and `|0|',
are called {\sl↑{numeric tokens}\/} because they represent numbers. The
other twelve---`|beginchar|', `|(|', etc.---are called {\sl↑{symbolic
tokens}\/}; such tokens can change their meaning while a \MF\ program runs,
but string tokens and numeric tokens always have a predetermined significance.
Notice that clusters of letters like `|beginchar|' are treated as a unit;
the same holds with respect to letters mixed with ↑{underline} characters,
as in `|mode_setup|'. Indeed,
the rules we are about to study will explain that clusters of other
characters like `|0.8|' and `|:=|' are also considered to be
indecomposable tokens. \MF\ has a definite way of deciding where one
token stops and another one begins.

It's often convenient to discuss ↑{grammatical rules} by formulating them in
a special notation that was introduced about 1960 by John ↑{Backus} and
Peter ↑{Naur}. Parts of speech are represented by named quantities in
↑{angle brackets}, and {\sl↑{syntax rules}\/} are used to express the ways
in which those quantities can be built~up from simpler units. For example,
here are three syntax rules that completely describe the possible forms of
numeric tokens:
\def\\#1{\thinspace{\tt#1}\thinspace}
\beginsyntax
<decimal digit>\is\\0\alt\\1\alt\\2\alt\\3\alt\\4\alt\\5\alt\\6%
  \alt\\7\alt\\8\alt\\9
<digit string>\is<decimal digit>\alt<digit string><decimal digit>
<numeric token>\is<digit string>\alt[.]<digit string>
  \alt<digit string>\\.<digit string>
\endsyntax
The first rule says that a \<decimal digit> is either `|0|' or `|1|' or
$\cdots$ or `|9|'; thus it must be one of the ten numerals. The next
rule says that a \<digit string> is either a \<decimal digit> or a
\<digit string> followed by a \<decimal digit>; thus it must be a sequence
of one or more digits. Finally, a \<numeric token> has one of three forms,
exemplified respectively by `|15|', `|.05|', and `|3.14159|'.

Syntax rules explain only the surface structure of a language, not the
underlying meanings of things. For example, the rules above tell us that
`|15|' is a \<numeric token>, but they don't imply that `|15|' has
any connection with the number fifteen. Therefore syntax rules are
generally accompanied by rules of {\sl↑{semantics}}, which ascribe
meanings to the strings of symbols that meet the conditions of the syntax.
In the case of numeric tokens, the principles of ordinary decimal notation
define the semantics, except that \MF\ deals only with numbers in a
limited range: A numeric token must be less than 4096, and its value is
always rounded to the nearest multiple of $1\over65536$. Thus, for example,
`|.1|'~does not mean $1\over10$, it means $6554\over65536$ (which is
slightly greater than $1\over10$). It turns out that the tokens
`|.099999|' and `|0.10001|' both have exactly the same meaning as
↑↑{numeric tokens, rounded values} ↑↑{numeric tokens, maximum value}
`|.1|', because all three tokens represent the value $6554\over65536$.

\dangerexercise Are the following pairs of numeric tokens equivalent
to each other, when they appear in \MF\ programs?
\ (a)~|0| and |0.00001|; \ (b)~|0.00001| and |0.00002|;
\ (c)~|0.00002| and |0.00003|; \ (d)~|04095.999999| and |10000|.
\answer (a) No, the second token represents $1\over65536$. \ (A token has
the same meaning as~`|0|' ↑↑{zero} if and only if its decimal value
is strictly less than $2↑{-17}=.00000\,76293\,94531\,25$.) \ (b)~Yes; both
tokens represent $1\over65536$, because 1~is the nearest integer to both
$.00001\times65536=.65536$ and $0.00002\times65536=1.31072$. \ (c)~No,
|0.00003| represents $2\over65536$. \ (d)~Yes, they both mean ``↑{enormous
number} that needs to be reduced''; \MF\ complains in both
cases and substitutes the largest legal numeric token.  \ (Rounding
4095.999999 to the nearest multiple of $1\over65536$ yields 4096,
which is too big.)

\MF\ converts each line of text into a sequence of tokens by repeating
the following rules until no more characters remain on the line:
\smallskip
\hang\textindent{1)}If the next character is a ↑{space}, or if it's a ↑{period}
(\thinspace`|.|'\thinspace) that isn't ↑↑{decimal point} followed by a
decimal digit or a period, ignore it and move on.

\hang\textindent{2)}If the next character is a ↑{percent sign}
(\thinspace`|%|'\thinspace), ignore it and also ignore everything else
that remains on the current line. \ (Percent signs therefore allow you to
write ↑{comments} that are unseen by \MF.)

\hang\textindent{3)}If the next character is a ↑{decimal digit} or a period
that's followed by a decimal digit, the next token is a numeric token,
consisting of the longest sequence of contiguous characters starting at
the current place that satisfies the syntax for \<numeric token> above.

\hang\textindent{4)}If the next character is a ↑{double-quote mark} (\thinspace
`|"|'\thinspace), the next token is a string token, consisting of all
characters from the current place to the next double-quote, inclusive.
\ (There must be at least one more double-quote remaining on the line,
otherwise \MF\ will complain about an ``↑{incomplete string}.'') \ A string
token represents the sequence of characters between the double-quotes.

\hang\textindent{5)}If the next character is a ↑{parenthesis} (\thinspace
`|(|' or `|)|'\thinspace), a comma (\thinspace`|,|'\thinspace), or a
semicolon (\thinspace`|;|'\thinspace), the next token is a symbolic token
consisting of that single character.

\hang\textindent{6)}Otherwise the next token is a symbolic token consisting
of the next character together with all immediately following characters
that appear in the same row of the following
↑↑{table of character classes} table:
\begindisplay \displayindent=0pt
|ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz|\hidewidth\cr
|<=>:|\|\cr
|`'|\cr
|+-|\cr
|/*\|\cr
|!?|\cr
|#&@$|\cr
|↑~|\cr
|[|\cr
|]|\cr
|{}|\cr
|.|&(see rules 1, 3, 6)\cr
|,  ;  (  )|&(see rule 5; these characters are ``loners'')\cr
|"|&(see rule 4 for details about string tokens)\cr
|0123456789|&(see rule 3 for details about numeric tokens)\cr
|%|&(see rule 2 for details about comments)\cr
\enddisplay

\noindent
The best way to learn the six rules about tokens is to work the following
exercise, after which you will be able to read any input file just as the
computer does.

\exercise What tokens does \MF\ find in the (ridiculous) line
\begindisplay
|xx3.1.6..[[a+-bc_d.e] ]"a %" <|\||>(($1. 5"+-""" % weird?|
\enddisplay
\answer \cstok{xx}, \cstok{3.1} (a numeric token), \cstok{.6} (another
numeric token), \cstok{..}, \cstok{[[}, \cstok{a}, \cstok{+-},
\cstok{bc\_d}, \cstok{e}, \cstok{]}, \cstok{]}, \chardef\"=`\"\cstok{\"a
\%\"} (a string token), \cstok{<\|>}, \cstok{(} (see rule~5), \cstok{(},
\cstok{\$}, \cstok{1} (a numeric token), \cstok{5} (likewise numeric),
\cstok{\"+-\"} (a string token), and \cstok{\"\"} (a string token that
denotes an empty sequence of characters).
All of these tokens are symbolic unless otherwise mentioned. \ (Notice that
four of the spaces and two of the periods were deleted by rule~1.
One way to verify that \MF\ finds precisely these tokens is to prepare a
test file that says `|isolated| |expression;|' on its first line and that
contains the stated text on its second line. Then respond to \MF's
error message by repeatedly typing `|1|', so that one token is deleted
at a time.)

\exercise Criticize the following statement: \MF\ ignores all spaces in the
input.
\answer The statement is basically true but potentially misleading. You can
insert any number of spaces {\sl between\/} tokens without changing the
meaning of a program, but you cannot insert a space in the {\sl middle\/}
of any token without changing something. You can delete spaces between
tokens {\sl unless\/} that would ``glue'' two adjacent tokens together.

\dangerexercise True or false: If the syntax for \<numeric token> were
changed to include a fourth alternative, `\<digit string>|.|', the meaning
of \MF\ programs would not change in any way.
\answer False. It may seem that this new sort of numeric token would be
recognized only in cases where the period is not followed by a digit,
hence the period would be dropped anyway by rule~1. However, the new rule
would have disastrous consequences in a line like `|draw| |z1..z2|'!


\endchapter

Yet wee with all our seeking could see no tokens.
 % of any such Wall.
\author PHILEMON ↑{HOLLAND},  {\sl ↑{Camden}'s Brittania\/} (1610)
% OED says page 518, but I couldn't find it there in the 1637 edition

\bigskip

Unpropitious tokens interfered.
\author WILLIAM ↑{COWPER},  {\sl ↑{Homer}'s Iliad\/} (1791) % Book 4 verse 455

\eject
\beginchapter Chapter 7. Variables

One of \MF's most important concepts is the notion of a
{\sl↑{variable}\/}---something that can take on a variety of different
values. Indeed, this is one of the most important concepts in all of
mathematics, and variables play a prominent r\↑ole in almost all
computer languages. The basic idea is that a program manipulates data,
and the data values are stored in little compartments of a computer's
memory. Each little compartment is a variable, and we refer to an item
of data by giving its compartment a name.

For example, the |io.mf| program for the letter {\manual\IOO} in Chapter~5
contains lots of variables. Some of these, like `|x1l|' and `|y1|', represent
coordinates. Others, like `|up|', represent
directions. The variables `|em#|' and `|thin#|' stand for physical,
machine-independent distances; the analogous variables `|em|' and `|thin|'
stand for the corresponding machine-dependent distances in units of pixels.

These examples indicate that different variables are often related to each
other. There's an implicit connection between `|em#|' and `|em|', 
between `|x1|' and `|y1|'; the `"penpos"' convention
sets up relationships between `|x1l|', `|x1|', and `|x1r|'. By choosing
the names of variables carefully, programmers can make their programs
much easier to understand, because the relationships between variables
can be made to correspond to the ↑↑{data structure} structure
of their names.

In the previous chapter we discussed tokens, the atomic elements from which
all \MF\ programs are made. We learned that there are three kinds of
tokens: numeric (representing numbers), string (representing text), and
symbolic (representing everything else).  Symbolic tokens have no
intrinsic meaning; any symbolic token can stand for whatever a programmer
wants it to represent.

Some symbolic tokens do, however, have predefined {\sl↑{primitive}\/}
meanings, when \MF\ begins its operations. For example, `|+|' stands
initially for ``plus,'' and `|;|' stands for ``finish the current
statement and move on to the next part of the program.''  It is customary
to let such tokens retain their primitive meanings, but any symbolic token
can actually be assigned a new meaning as a program is performed. For
example, the definition of `|test_I|' in |io.mf| makes that token stand
for a {\sl↑{macro}}, i.e., a subroutine. We'll see later that you can
instruct \MF\ to `|let| |plus=+|', after which `|plus|' will act just
like `|+|' did.

\MF\ divides symbolic tokens into two categories, depending on their
current meaning. If the symbolic token currently stands for one of \MF's
primitive operations, or if it has been defined to be a macro, it is
called a {\sl↑{spark}\/}; otherwise it is called a {\sl↑{tag}}. Almost
all symbolic tokens are tags, because only a few are defined to be sparks;
however, \MF\ programs typically involve lots of sparks, because sparks
are what make things happen. The symbolic tokens on the first five lines
of |io.mf| include the following sparks:
\begintt
mode_setup  ;  :=  /  define_pixels  (  ,  )
\endtt
and the following tags:
\begintt
em  #  pt  cap  thin  thick  o
\endtt
(some of which appear several times). Tags are used to designate variables,
but sparks cannot be used within a variable's name.

Some variables, like `|em#|', have names that are made from more than one token;
in fact, the variable `|x1l|' is named by three tokens, one of which is
numeric. \MF\ has been designed so that it is easy to make compound names
that correspond to the relations between variables. Conventional programming
languages like ↑{Pascal} would refer to `|x1l|' by the more
cumbersome notation `|x[1].l|'; it turns out that `|x[1].l|' is an
acceptable way to designate the variable |x1l| in a \MF\ program, but the
shorthand form `|x1l|' is a great convenience because such variables
are used frequently.

Here are the formal rules of syntax by which \MF\ understands the names of
variables:
\def\\#1{\thinspace{\tt#1}\thinspace}
\beginsyntax
<variable>\is<tag><suffix>
<suffix>\is<empty>\alt<suffix><subscript>\alt<suffix><tag>
<subscript>\is<numeric token>\alt\\{\char`\[}<numeric expression>\\]
\endsyntax
First comes a tag, like `|x|'; then comes a {\sl↑{suffix}\/} to the tag,
like `|1l|'.
The suffix might be empty, or it might consist of one or more subscripts
or tags that are tacked on to the original tag. A {\sl↑{subscript}\/} is
a numeric index that makes it possible to construct ↑{arrays} of related
variables. The subscript is either a single numeric token, or it is a formula
enclosed in square ↑{brackets}; in the latter case the formula should produce a
↑↑|[| numeric value. For example, `|x[1]|' and `|x[k]|' and `|x[3-2k]|' all mean
↑↑|]| the same thing as `|x1|', if\/ |k|~is a variable whose value is~1. But
`|x.k|' is not the same; it is the tag~`|x|' suffixed by the tag~`|k|',
not the tag~`|x|' subscripted by the value of variable~|k|.

\danger The variables `|x1|' and `|x01|' and `|x1.00|' are identical.
Since any numeric token can be used as a subscript, fractional indices
are possible; for example, `|x1.5|' is the same as `|x[3/2]|'. Notice
that `|B007|' and `|B.007|' are {\sl not\/} the same variable, because
the latter has a fractional subscript.

\danger \MF\ makes each \<suffix> as long as possible. In other words,
a \<suffix> is always extended if it is followed by a \<subscript>
or a~\<tag>.

\dangerexercise Explain how to type a reference to the doubly subscripted
variable `|a[1][5]|' without using square brackets.
\answer You can put a space between the subscripts, as in `|a1|~|5|'. \
(We'll see later that a ↑{backslash} acts as a null symbol,
hence `|a1\5|' is another solution.)

\dangerexercise Is it possible to refer to {\sl any\/} variable without
using square brackets?
\answer No; |a[-1]| can't be accessed without using |[| and |]|. The
only other form of \<subscript> is \<numeric token>, which can't be
negative. \ (Well, strictly speaking, you could say `|let|~|?=[;|
|let|~|??=]|' and then refer to `|a?-1??|'; but that's cheating.)

\dangerexercise John H. ↑{Quick} (a student) used `|a.plus1|' as the name
of a variable at the beginning of his program; later he said `|let|
|plus=+|'. How could he refer to the variable `|a.plus1|' after that?
\answer Assuming that `|+|' was still a spark when he said `|let|~|plus=+|',
he can't refer to the variable `|a.plus1|' unless he changes the meaning of
|plus| again to make it a~tag. \ (We will eventually learn a way to do this
without permanently clobbering |plus|, as follows: `↑|begingroup| ↑|save|
|plus;| |a.plus1| ↑|endgroup|'.)

\danger \MF\ has several special variables called {\sl↑{internal
quantities}\/} that are intimately wired-in to the computer's behavior.
For example, there's an internal quantity called `↑|fontmaking|' that controls
whether or not a |TFM| file is produced; another one called `↑|tracingtitles|'
governs whether or not titles like |"The| |letter|~|O"| appear on your
terminal; still another one called `↑|smoothing|' affects the digitization of
curves. \ (A complete list of \MF's internal quantities appears in
Chapter~xx.) \ The name of an internal quantity acts like a tag, but
internal quantities cannot be suffixed. Thus, the syntax rule for \<variable>
should actually be replaced by a slightly more complicated pair of rules:
\beginsyntax
<variable>\is<external tag><suffix>\alt<internal quantity>
<tag>\is<external tag>\alt<internal quantity>
\endsyntax

\dangerexercise True or false: Every \<variable> is a legal \<suffix>.
\answer True. \ (But a \<suffix> is not always a \<variable>.)

\ddanger The `|[|' and `|]|' that appear in the syntax for \<subscript>
stand for any symbolic tokens whose current meanings are the same as
\MF's primitive meanings of left and right bracket, respectively;
those tokens don't necessarily have to be brackets. Conversely, if the
meanings of the tokens `|[|' and `|]|' have been changed, brackets cannot
be used to delimit subscripts. Similar remarks apply to all of the
symbolic tokens in all of the syntax rules from now on. \MF\ doesn't look
at the form of a token; it considers only a token's current meaning.

The examples of \MF\ programs in this book have used two different
typographic conventions. Sometimes we refer to variables by using
↑{italic type} and/or genuine subscripts, e.g., `"em"' and `$x↓{2r}$';
but sometimes we refer to those same variables by using a ↑{typewriter}-like
style of type, e.g., `|em|' and~`|x2r|'. In general, the typewriter style
is used when we are mainly concerned with the way a programmer is supposed
to type something that will appear on the terminal or in a file; but fancier
typography is used when we are focusing on the meaning of a program rather
than its ASCII representation. It should be clear how to convert the fancier
form into tokens that \MF\ can actually understand.

\danger In general, we shall use italic type only for tags (e.g., "em",
"x", "r"), while boldface and roman type will be used for sparks
(e.g., @draw@, @fill@, cycle, rotated, sqrt). Tags that consist of special
characters instead of letters will sometimes get special treatment;
for example, |em#| and |z2'| might be rendered $"em"\0$ and $z'↓2$,
respectively.

The variables we've discussed so far have almost always had numbers as their
values, but in fact \MF's variables are allowed to assume values of eight
different ↑{types}. A variable can be of type
\nobreak\smallskip
\item\bull↑{boolean}, representing the values `↑{true}' or `↑{false}';
\item\bull↑{string}, representing sequences of ASCII characters;
\item\bull↑{path}, representing a (possibly curved) line;
\item\bull↑{pen}, representing the shape of a pen nib;
\item\bull↑{picture}, representing an entire pattern of pixels;
\item\bull↑{transform}, representing the operations of scaling, rotating,
	shifting, reflecting, and/or slanting;
\item\bull↑{pair}, representing two numbers (e.g., a point or a vector);
\item\bull↑{numeric}, representing a single number.
\smallskip\noindent
If you want a variable to represent something besides a number, you must
first give a {\sl↑{type declaration}\/} ↑↑{declarations} that states
what the type will be. But if you refer to a variable whose type has not
been declared, \MF\ won't complain, unless you try to use it in a way that
demands a non-numeric value.

Type declarations are easy. You simply name one of the eight types,
then you list the variables that you wish to declare for that type.
For example, the declaration
\begindisplay
@pair@ "right", "left", $a.p$
\enddisplay
says that "right" and "left" and $a.p$ will be variables of type @pair@,
so that equations like
\begindisplay
$"right"=-"left"=2a.p=(1,0)$
\enddisplay
can be given later. These equations, incidentally, define the values
$"right"=(1,0)$, $"left"=(-1,0)$, and $a.p=(.5,0)$. \ (Plain \MF\
has the stated values of "right" and "left" already built~in.)

The rules for declarations are slightly trickier when subscripts are
involved, because \MF\ insists that all variables whose names are identical
except for subscript values must have the same type. It's possible to
set things up so that, for example, $a$~is numeric, $a.p$ is a pair,
$a.q$ is a pen, $a.r$ is a path, and $a↓1$ is a string; but if $a↓1$
is a string, then all other variables $a↓2$, $a↓3$, etc., must also be
strings. In order to enforce this restriction, \MF\ allows only
``collective'' subscripts, represented by empty brackets `↑|[]|',
to appear in type declarations. ↑↑{collective subscripts} For example,
\begintt
path r, r[], x[]arc, f[][]
\endtt
declares $r$ and all variables of the forms $r[i]$, $x[i]"arc"$,
and $f[i][j]$ to be path variables. This declaration doesn't affect
the types or values of other variables like $r[\,]"arc"$; it only
affects the variables specifically mentioned.

Declarations destroy all previous values of the variables being defined.
For example, the path declaration above makes $r$ and $r[i]$ and $x[i]"arc"$
and $f[i][j]$ undefined, even if those variables previously had paths
as their values. The idea is that these variables will start out with a
clean slate so that they can receive appropriate new values based on
subsequent equations. ↑↑{value, disappearance of}

\exercise Numeric variables don't need to be declared. Therefore is there
ever any reason for saying `|numeric| |x|'\thinspace?
\answer Yes, because it removes any existing value that $x$ may have
had, of whatever type; otherwise you couldn't safely use $x$ in a
numeric equation. It's wise to declare numeric variables when you're
not sure about their former status, and when you're sure that you don't
care what their previous value was. A numeric declaration together with a
comment also provides useful documentation. \ (Incidentally, `|numeric|~|x|'
doesn't affect other variables like `|x2|' or `|x.x|' that might be present.)

\danger The formal syntax rules for type declarations explain these
grammatical conventions precisely. If the symbolic token that begins a
declared variable was previously a spark, it loses its former meaning and
immediately becomes a tag.
\beginsyntax
<declaration>\is<type><declaration list>
<type>\is[boolean]\alt[string]\alt[path]\alt[pen]
  \alt[picture]\alt[transform]\alt[pair]\alt[numeric]
<declaration list>\is<declared variable>
  \alt<declaration list>[,]<declared variable>
<declared variable>\is<symbolic token><declared suffix>
<declared suffix>\is<empty>\alt<declared suffix><tag>
  \alt<declared suffix>\\{\char`\[}\\]
\endsyntax

\dangerexercise Find three errors in the supposed declaration
`|transform| |t42,24t,,t,path|'.
\answer (a)~The `|42|' is illegal because subscripts must be collective.
\ (b)~The `|24|' is illegal because a \<declared variable> must start with
a \<symbolic token>, not a numeric token. \ (c)~There's nothing wrong with
the consecutive commas; the second comma begins a \<declared variable>, so
it loses its former meaning and becomes a tag. Thus \MF\ tries to declare
the variable `|,t,path|'. However, `|path|' cannot appear in a suffix,
since it's a spark. \ (Yes, this is admittedly tricky. Computers follow rules.)

\endchapter

A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Chapter 8. Algebraic\\Expressions

\MF\ programmers express themselves algebraically by writing algebraic
formulas called {\sl↑{expressions}}. The formulas are algebraic in the
sense that they involve variables as well as constants. By combining
variables and constants with appropriate mathematical operations, a
programmer can specify an amazing variety of things with comparative ease.

We have already seen many examples of expressions; our goal now is to make
a more systematic study of what is possible. The general idea is that an
expression is either a ↑{variable} (e.g., `$x↓1$'\thinspace) or a
↑{constant} (e.g., `20'\thinspace), or it consists of an ↑{operator}
(e.g., `$+$'\thinspace) together with its ↑{operands} (e.g.,
`$x↓1+20$'\thinspace). The operands are, in turn, expressions built~up in
the same way, perhaps enclosed in ↑{parentheses}. For example,
`$(x↓1+20)/(x↓2-20)$' is an expression that stands for the quotient of two
subexpressions.  It is possible to concoct extremely complicated algebraic
expressions, but even the most intricate constructions are built from
simple parts in simple ways.

Mathematicians spent hundreds of years developing good ways to write formulas;
then computer scientists came along and upset all the time-honored traditions.
The main reason for making a change was the fact that computers find it
difficult to deal with two-dimensional constructions like
\begindisplay
$\displaystyle{x↓1+20\over x↓2-20}+\sqrt{a↑2-{2\over3}\sqrt b}.$
\enddisplay
One-dimensional sequences of tokens are much easier to input and to decode;
hence programming languages generally put such formulas all on one line,
↑↑{sqrt} by inserting parentheses, brackets, and asterisks as follows:
\begintt
(x[1]+20)/(x[2]-20)+sqrt(a**2-(2/3)*sqrt(b)).
\endtt
\MF\ will understand this formula, but it also accepts a notation that
is shorter and closer to the standard conventions of mathematics:
\begintt
(x1+20)/(x2-20)+sqrt(a**2-2/3sqrt b).
\endtt
We observed in the previous chapter that \MF\ allows you to write `|x2|'
instead of `|x[2]|'; similarly, you can write `|2x|' instead of `|2*x|'
and `|2/3x|' instead of `|(2/3)*x|'. Such operations are extremely common
in \MF\ programs, hence the language has been set up to facilitate them.
On the other hand, \MF\ doesn't free you from all the inconveniences of
computer languages; you must still write `|x*k|' for the ↑{product} of
$x$ times~$k$, and `|x[k]|' for the variable $x$~subscripted by~$k$,
in order to avoid confusion with the suffixed variable `|x.k|'.

We learned in the previous chapter that there are eight types of
variables: numeric, boolean, string, and so~on. The same types apply
to expressions; \MF\ deals not only with numeric expressions but also
with boolean expressions, string expressions, and the others. For example,
`$(0,0)\to(x↓1,y↓1)$'
is a path-valued expression, formed by applying the operator `$\to$' to the
subexpressions `$(0,0)$' and `$(x↓1,y↓1)$'; these subexpressions, in turn,
have values of type ``pair,'' and they have been built up from values of
type ``numeric.'' Each operation produces a result whose type can be
determined from the types of the operands; furthermore the simplest
expressions (variables and constants) always have a definite type.
Therefore the machine always knows what type of quantity it is dealing
with, after it has evaluated an expression.

If an expression contains several operators, \MF\ has to decide which
↑↑{order of operations}
operation should be done first. For example, in the expression `$a-b+c$'
it is important to compute `$a-b$' first, then to add~$c$; if `$b+c$' were
computed first, the result `$a-(b+c)$' would be quite different from the
usual conventions of mathematics. On the other hand, mathematicians
usually expect `$b/c$' to be computed first in an expression like
`$a-b/c$'; multiplications and divisions are usually performed before
additions and subtractions, unless the contrary is specifically indicated
by parentheses as in `$(a-b)/c$'. The general rule is to evaluate
subexpressions in parentheses first, then to do operations in order of
their ``↑{precedence}''; if two operations have the same precedence the
left one is done first. For example, `$a-b/c$' is equivalent to
`$a-(b/c)$' because division takes precedence over subtraction; but
`$a-b+c$' is equivalent to `$(a-b)+c$' because left-to-right order is
used on operators of equal precedence.

It's convenient to think of operators as if they are tiny ↑{magnets} that
attract their operands; the magnets for `$\ast$' and `/' are stronger
than the magnets for `$+$' and `$-$', so they stick to their operands more
tightly and we want to perform them first.

\MF\ distinguishes four (and only four) levels of precedence. The
strongest magnets are those that join `2' to~`$x$' and `sqrt' to `$b$'
in expressions like `$2x$' and `sqrt$\,b$'. The next strongest are
multiplicative operators like `$\ast$' and~`/'; then come the additive
operators like `$+$' and~`$-$'. The weakest magnets are operators like
`$\to$' or `$<$'. For example, the expression
\begindisplay
$a+{\rm sqrt}\,b/2x<c$
\enddisplay
is equivalent to the fully parenthesized formula
\begindisplay
$\bigl(a+\bigl(({\rm sqrt}\,b)/(2x)\bigr)\bigr)<c$.
\enddisplay

\exercise Insert parentheses into the formula `|z1+z2..z3/4*5..z6-7*8z9|',
to show explicitly in what order \MF\ will do the operations.
\answer |((z1+z2)..((z3/4)*5))..(z6-(7*(8z9)))|.

\danger High-school algebra texts often avoid parentheses inside of
parentheses by using ↑{braces} and ↑{brackets}; many people
have been trained to write
\begindisplay
$\{a+[({\rm sqrt}\,b)/(2x)]\}<c$
\enddisplay
instead of the fully parenthesized formula above. However, professional
mathematicians usually stick to only one kind of parentheses, because
braces and brackets have other meanings that are more important. In this
respect \MF\ is like the professionals: It reserves curly braces `|{}|'
and square brackets `|[]|' for special purposes, so you should not
try to substitute them for parentheses.

\ddanger If you really want alternatives to parentheses, there is actually
a way to get them. You can say, for example,
\begintt
delimiters [[ ]];  delimiters {{  }}
\endtt
after which double brackets and braces can be used in formulas like
\begintt
{{a+[[(sqrt b)/(2x)]]}}<c.
\endtt
The symbolic token `|{{|' has no relation to `|{|', and it
has no primitive meaning, hence you are free to define it in any way you
like; the ↑@delimiters@ command defines a new pair of delimiters. In formulas
with mixed delimiters as defined here, \MF\ will check that `|[[|' matches only
with~`|]]|', `|{{|'~only with~`|}}|', and `|(|'~only with~`|)|'; thus you
can more easily detect errors in large expressions. However, it's usually
unnecessary to have any delimiters other than parentheses, because large
expressions are rare, and because the rules of operator precedence make
most parentheses superfluous.

If you're reading this chapter carefully, you may be thinking, ``Hey wait!
Isn't there a contradiction? A minute ago I was told that `|2/3x|' stands
for `|(2/3)*x|', but now the rules of precedence appear to state that
`|2/3x|' really stands for `|2/(3x)|'. What gives?'' Indeed, you have an
excellent point; but there is no contradiction, because of another rule that
hasn't been mentioned yet. When two {\sl numeric tokens\/} are divided, the
↑↑{division of numeric tokens} magnetism of `|/|' is stronger than usual;
in this case `|/|' has the same precedence as the implied multiplication
operator in `|3x|'. Hence the operations in `|2/3x|' are carried out from
left to right, as stated previously. \ (This is a good rule because it
is almost always what a \MF\ programmer wants. However, one should bear
in mind that `|a/3x|' means `|a/(3x)|' when |a| is {\sl not\/} a numeric token.)

Because of the rule in the previous paragraph, the \MF\ programs in this
book often say `${2\over3}x$' for what would be typed `|2/3x|' in a file.
Such built-up ↑{fractions} are never used except when the numerator and
denominator are both numbers; a construction like `|a/3x|' will always be
rendered as `$a/3x$', not~`$\,{a\over3x}\,$'.

\MF\ knows how to do dozens of operations that haven't been mentioned yet
in this book. Let's take a look at some of them, so that we will know
they are available in case of need. It will be most instructive and
most fun to learn about expressions by interacting with the computer;
↑↑"tracingonline" ↑↑@scrollmode@ ↑↑@forever@ ↑↑@scantokens@ ↑↑{readstring}
↑↑@message@
therefore you should prepare the following short file, called ↑|expr.mf|:
\begintt
string s[]; s1="abra";
path p[]; p1=(0,0)..(3,3); p2=(0,0)..(3,3)..cycle;
tracingonline:=1; scrollmode;
forever: message "gimme an expr: "; s0:=readstring;
show scantokens s0; endfor
\endtt

\danger It isn't necessary to understand what's in |expr.mf| when you read
this chapter for the first time, because it uses \MF\ in ways that will be
explained carefully later. But here is a translation, in case you're
curious: Line~1 declares all variables of the form $s↓k$ to be strings, and
sets $s↓1$ to the value |"abra"|. Line~2 declares all variables of the
form~$p↓k$ to be paths, and sets $p↓1$ and~$p↓2$ to simple example paths.
Line~3 tells \MF\ to print diagnostic information ↑{online}, i.e., on the
terminal as well as in the ↑{log file}; it also establishes
`@scrollmode@', which means that the computer won't stop after error
messages. Lines 4 and~5 set up an infinite loop in which \MF\ reads an
expression from the terminal and shows the corresponding value.

\outer\def\begindemo{$$\advance\baselineskip by2pt
  \catcode`\"=\other
  \halign\bgroup\indent\hbox to 160pt{\tt##\hfil}&\tt##\hfil\cr
  \noalign{\vskip-2pt}}
\outer\def\enddemo{\egroup$$}
\def\werror{\ \rm(with error message)}
\def\werrors{\ \rm(with error messages)}
\def\demohead{\it\kern-2pt You type&\it\kern-1pt And the result is\cr
  \noalign{\nobreak\vskip2pt}}

If you start \MF\ and type `|expr|' when it asks for an input file name,
it will read the file |expr.mf| and then it will say `↑|gimme| |an|~|expr|'. Here's
where the fun starts: You can type any expression, and \MF\ will compute
and display its value. Try it; type `|2+2|' and \<return>, obtaining the
value~`|>>|~|4|'. Isn't that amazing? Here are some more things to try:
\begindemo
\demohead
1.2-2.3&-1.1\cr
1.3-2.4&-1.09999\cr
1.3*1000&1300.0305\cr
2.4*1000&2399.9939\cr
3/8&0.375\cr
.375*1000&375\cr
1/3&0.33333\cr
1/3*3&0.99998\cr
0.99999&0.99998\cr
1-epsilon&0.99998\cr
1/(1/3)&3.00005\cr
1/3.00005&0.33333\cr
.1*10&1.00006\cr
1+4epsilon&1.00006\cr
\enddemo
These examples illustrate the small errors that occur because \MF\ does
``fixed binary'' ↑{arithmetic} using integer multiples of $1\over65536$.
The result of $1.3-2.4$ is not quite the same as $-1.1$, because |1.3| is
a little bit larger than~$13\over10$ and |2.4| is a little smaller
than~$24\over10$. Small errors get magnified when they are multiplied by
1000, but even after magnification the discrepancies are negligible because
they are just tiny fractions of a pixel. You may be surprised that
1/3~times~3 comes out to be .99998 instead of .99999; the truth is that both
|0.99999| and |0.99998| represent the same value, namely $65535\over65536$; \MF\
displays this value as |0.99998| because it is closer to .99998 than to
.99999. Plain \MF\ defines ↑"epsilon" to be $1\over65536$, the smallest
representable number that is greater than zero; therefore |1-epsilon|
is $65535\over65536$, and |1+4epsilon| is $65540\over65536$.
\begindemo
\demohead
4096&4095.99998\werror\cr
infinity&4095.99998\cr
1000*1000&32767.99998\werror\cr
infinity+epsilon&4096\cr
100*100&10000\cr
.1(100*100)&1000.06104\cr
(100*100)/3&3333.33333\cr
\enddemo
\MF\ will complain that an `|Enormous| ↑↑{enormous number} |number| |has|
|been| |reduced|' when you try to introduce constants that are 4096 or~more.
Plain \MF\ defines ↑"infinity" to be $4096-"epsilon"$, which is the largest
legal numeric token. On the other hand, it turns out that larger numbers
can actually arise when an expression is being evaluated; \MF\ doesn't
worry about this unless the resulting magnitude is at least 32768.

\dangerexercise If you try `|100*100/3|' instead of `|(100*100)/3|', you
get `|3333.33282|'. Why?
\answer The fraction |100/3| is evaluated first (because such divisions
take precedence); the rounding error in this fraction is then magnified by~100.

\ddanger Sometimes \MF\ will compute things more accurately than you would
expect from the examples above, because many of its internal calculations
are done with multiples of $2↑{-28}$ instead of $2↑{-16}$. For example,
if $t=3$ the result of `|1/3t|' will be exactly~1
(not 0.99998); the same thing happens if you write `|1/3(3)|'.

Now let's try some more complicated expressions, using undefined
variables as well as constants. \ (Are you actually trying these
examples, or are you just reading the book? It's far better to type
them yourself and to watch what happens; in fact, you're also allowed
to type things that {\sl aren't\/} in the book!)
\begindemo
\demohead
b+a&a+b\cr
a+b&a+b\cr
b+a-2b&a-b\cr
2(a-b+.5)&2a-2b+1\cr
.5(b-a)&-0.5a+0.5b\cr
.5[a,b]&0.5a+0.5b\cr
1/3[a,b]&0.66667a+0.33333b\cr
0[a,b]&a\cr
a[2,3]&a+2\cr
t[a,a+1]&a+t\cr
a*b&b\werror\cr
1/b&b\werror\cr
\enddemo
\MF\ has a preferred way to arrange variables in order when they are added
together; therefore `$a+b$' and `$b+a$' give the same result. Notice that
the ↑{mediation} construction `$.5[a,b]$' specifies a number that's halfway
between $a$ and~$b$, as explained in Chapter~2. \MF\ does not allow you to
↑{multiply} two unknown numeric quantities together, nor can you ↑{divide} by an
unknown numeric; all of the unknown expressions that \MF\ works with must be
``↑{linear forms},'' i.e., they must be sums of variables with constant
coefficients, plus an optional constant. \ (You might want to try typing
`|t[a,b]|' now, in order to see what error message is given.)
\begindemo
\demohead
sqrt 2&1.41422\cr
sqrt 100&10\cr
sqrt 100*100&1000\cr
sqrt(100*100)&100\cr
sqrt 100(100)&100\cr
sqrt sqrt 100(100)&10\cr
sqrt .01&0.09998\cr
0.09998**2&0.01\cr
2**1/2&1.41422\cr
sqrt 2**2&2\cr
sqrt -1&0\werror\cr
sqrt a&a\werror\cr
\enddemo
Since ↑|sqrt| has more ``magnetism'' than |*|, the formula |sqrt|~|100*100|
↑↑{square roots}
is evaluated as |(sqrt|~|100)*100|; but in `|sqrt|~|100(100)|' the
|100(100)| is computed first. The reason is that `|(sqrt|~|100)(100)|' isn't
a legal expression, so the operations in `|sqrt|~|100(100)|' must be carried
out from right to left. If you are unsure about the order of evaluation,
↑↑|**| you can always insert parentheses; but you'll find that \MF's rules of
precedence are fairly natural as you gain experience.

\exercise Is `|sqrt|~|2**2|' computed as `|(sqrt|~|2)**2|' or as
`|sqrt(2**2)|'\thinspace?
\answer A |sqrt| takes precedence over any operation with two operands, hence
the machine computes `|(sqrt|~|2)**2|'; \MF\ was somewhat lucky that the
answer turned out to be exactly~2. \ (The |sqrt| operation computes the
nearest multiple of $1\over65536$, and the rounding error in this quantity
is magnified when it is squared. If you try |sqrt|~|3**2|, you'll get
|3.00002|; also |sqrt|~|2**4| turns out to be |4.00002|.) \ Incidentally,
the ↑|**| operation of plain \MF\ has the same precedence as |*| and~|/|;
hence `|x*y**2|' means the same as `|(x*y)**2|', and `|-x**2|' means
`|(-x)**2|', contrary to the conventions of {\eightrm ↑{FORTRAN}}.

Some \MF\ expressions have `↑{true}' or `↑{false}' values, instead of numbers;
we will see later that they can be used to adapt \MF\ programs to special
conditions.
\begindemo
\demohead
0<1&true\cr
0=1&false\cr
a+1>a&true\cr
a>=b&false\werror\cr
"abc"<="b"&true\cr
"B">"a!"&false\cr
"b">"a?"&true\cr
(1,2)<>(0,4)&true\cr
(1,2)<(0,4)&false\cr
(1,a)>(0,b)&true\cr
numeric a&true\cr
known a&false\cr
not(pen a)&true\cr
known "a" and numeric 1&true\cr
(0>1) or (a<a)&false\cr
0>1 or a<a&a\werrors\cr
\enddemo
↑↑{not} ↑↑@and@ ↑↑@or@ ↑↑{comparison}
The tokens `↑|>=|', `↑|<=|', and `↑|<>|' stand respectively for the
↑{relations} ↑{greater-than-or-equal-to}, ↑{less-than-or-equal-to}, and
↑{unequal-to}. When strings are compared, \MF\ uses the order of words in
a dictionary, except that it uses ASCII code to define ordering of individual
characters; thus, all uppercase letters are considered to be less than all
lowercase letters. \ (See Appendix~C\null.) \ When pairs of numbers are
compared, \MF\ considers only the $x$~coordinates, unless the $x$~coordinates
are equal; in the latter case it compares the $y$~coordinates. The type
of an expression can be ascertained by an expression like `|pair|~|a|',
which is true if and only if |a|~is a pair. ↑↑{pair} ↑↑{numeric} ↑↑{pen}
The expression `|known|~|a|' ↑↑{known} is true if and only if the value
of~|a| is fully known.

\dangerexercise What causes the error messages in `|0>1|~|or|~|a<a|'\thinspace?
\answer Since `↑@or@' has stronger precedence than `$<$' or `$>$', ↑↑|<| ↑↑|>|
\MF\thinspace\ tries to evaluate this expression by putting things in
parentheses as follows: `$(0>(1\mathbin{\bf or}a))<a$'. Now
`$1\mathbin{\bf or}a$' makes no sense, because `@or@' operates only on
booleans; in such cases \MF\ uses the right operand~`$a$' as the result. Then
`$\mkern1mu0>a$' is indeterminate because $a$~is unknown; \MF\ treats this as
false. Finally `${\rm false}<a$' is another illegal combination of types.

\danger The rest of this chapter is entirely preceded by ``dangerous bend''
signs, so you can safely omit it on first reading (unless you're hooked
and can't stop).

\danger \MF\ expressions can include many operations that are
less familiar but still useful. For example, the ↑{max} and ↑{min}
operations compute the ↑{maximum} and ↑{minimum} of numbers, strings,
or pairs:
\begindemo
\demohead
max(1,-2,4)&4\cr
min(1,-2,4)&-2\cr
max("a","b","ab")&"b"\cr
min("a","b","ab")&"a"\cr
max(1)&1\cr
max((1,5),(0,6),(1,4))&(1,5)\cr
min((1,5),(0,6),(1,4))&(0,6)\cr
max(.5a+1,.5a-1)&0.5a+1\cr
\enddemo
Numbers can be converted to ↑{integers} in a variety of ways:
\begindemo
\demohead
floor 3.14159&3\cr
floor -3.14159&-4\cr
floor -epsilon&-1\cr
ceiling 3.14159&4\cr
ceiling -3.14159&-3\cr
round 3.14159&3\cr
round -3.14159&-3\cr
round(1.1,2.8)&(1,3)\cr
round(3.5,-3.5)&(4,-3)\cr
round a&a+0.5\werror\cr
8 mod 3&2\cr
-8 mod 3&1\cr
.8 mod .3&0.2\cr
\enddemo
The `↑{floor}' operation computes the ↑{greatest integer} that is less than
or equal to its operand; this quantity is often denoted by $\lfloor x\rfloor$
in mathematics texts. Plain \MF\ also includes the analogous `↑{ceiling}'
operation $\lceil x\rceil$, which is the ↑{least integer} greater than or
equal to~$x$.  Furthermore `↑{round}$\,x$' is the integer nearest to~$x$;
plain \MF\ computes this by using the formula $\lfloor x+.5\rfloor$, and
applies it to both components of a pair if a pair is being rounded. The
↑{remainder} of $x$ with respect to~$y$, written `$x\bmod y$', ↑↑{mod} is
calculated by using the formula $x-y\lfloor x/y\rfloor$.
\begindemo
\demohead
abs -7&7\cr
abs(3,4)&5\cr
length(3,4)&5\cr
3++4&5\cr
300++400&500\cr
sqrt(300**2 + 400**2)&181.01933\werrors\cr
1++1&1.4142\cr
0 ++ -7&7\cr
5+-+4&3\cr
\enddemo
↑↑{abs} ↑↑{length} ↑↑{absolute value}
The `↑|++|' operation is called {\sl↑{Pythagorean addition}\/}; $a\pyth+b$
is the same thing as $\sqrt{a↑2+b↑2}$. Most of the ↑{square root} operations
in computer programs could probably be avoided if $++$ were more widely
available, because people seem to want square roots primarily when they
are computing distances. Notice that $a\pyth+b\pyth+c=
\sqrt{a↑2+b↑2+c↑2}$; we have the identity $(a\pyth+b)\pyth+c=a\pyth+(
b\pyth+c)$ as well as $a\pyth+b=b\pyth+a$. It is better to use Pythagorean
addition than to calculate $\sqrt{a↑2+b↑2}$, because the computation of
$a↑2$ and $b↑2$ might produce numbers that are too large even when
$a\pyth+b$ is rather small. There's also an inverse operation,
↑{Pythagorean subtraction}, which is denoted by `↑|+-+|'; the quantity
$a\mathbin{+{-}+}b$ is equal to $\sqrt{a↑2-b↑2}$.

\dangerexercise When the author was preparing these examples he typed
`|0++-7|' and was surprised to get the answer `|0|'. Why should this not
have been a surprise?
\answer The token `|++-|' is undefined, so it is a tag; therefore
|++-7| is a subscripted variable, which was multiplied by zero.

\ddangerexercise (For mathematicians.) \ Although the Pythagorean addition
operation is associative and commutative, \MF\ says that
$5\pyth+4\pyth+2\pyth+2=7=2\pyth+2\pyth+4\pyth+5$ yet
$2\pyth+4\pyth+5\pyth+2=6.99998$. Why?
\answer The associative law is valid for exact computations, but not
for rounded computations. For example, it fails even in the case of
multiplication, since $(.1\ast.1)\ast10=0.09995$ while $.1\ast(.1\ast10)=.1$
when products are rounded to the nearest multiples of $1\over65536$.
However, this observation doesn't quite explain the stated example, which
would have yielded 7 in all cases if \MF\ had computed $2\pyth+4$ with
full accuracy!  The closest approximation to $\sqrt{20}$ is ↑↑{accuracy}
$4{30942\over65536}$, but $2\pyth+4$ turns out to be $4{30941\over65536}$
instead. \MF\ computes the absolutely best possible approximations to the
true answers when it does multiplications, divisions, and square roots,
but not when it does Pythagorean operations.

\danger \MF\ uses the names `↑{sind}' and `↑{cosd}' for the ↑{trigonometric}
functions ↑{sine} and ↑{cosine}, because \MF's operations are designed to
deal with angles expressed in degrees. But it turns out that programmers
rarely need to refer to sines and cosines explicitly, because the `↑{dir}'
and `↑{angle}' functions provide most of what a font designer needs.
\begindemo
\demohead
sind 30&0.5\cr
cosd 30&0.86603\cr
sind -30&-0.5\cr
cosd 360&1\cr
sind 10 ++ cosd 10&1\cr
dir 30&(0.86603,0.5)\cr
dir -90&(0,-1)\cr
angle(1,1)&45\cr
angle(1,2)&63.43495\cr
angle(1,-2)&-63.43495\cr
sind63.43495/cosd63.43495&1.99997\cr
angle up&90\cr
angle left&180\cr
angle(-1000,-epsilon)&-180\cr
angle dir 60&60.00008\cr
angle(0,0)&0\werror\cr
\enddemo
Plain \MF\ defines `dir$\,x$' to be the pair of values $(\mathop{\rm cosd}x,
\mathop{\rm sind}x)$; this is a vector that points $x$~degrees above the
rightward horizon. Conversely, the `angle' operator determines the angle
that corresponds to a given vector.

\ddanger Logarithms and exponentials are computed with respect to an
unusual base, designed to enhance the accuracy of calculations
involving fixed-radix numbers in \MF's range. The values ↑{mlog}$\,x=256\ln x$
and ↑{mexp}$\,x=e↑{x/256}$ produce reasonably good results when
$x\mathbin{\ast\ast}y$ is computed by the formula mexp$(y\ast\mathop{\rm
mlog} x)$.
\begindemo
\demohead
mlog 2&177.44568\cr
mexp mlog 2&2\cr
mexp 8 mlog 2&256\cr
mexp 256&2.71828\cr
mlog 2.71828&255.99954\cr
mlog 2.71829&256.00098\cr
%mlog mexp 2&1.99998\cr
15 mlog 2&2661.68518\cr
mexp 2661.68518&32767.99998\cr
mexp 2661.68519&32767.99998\werror\cr
mexp-2661.68519&0.00003\cr
\enddemo

\danger \MF\ also generates two flavors of random numbers. It is very
unlikely that you will get the particular values shown in the following
examples, when you do the experiment yourself, because the results come
out different each time the computer is asked for a new random number
(unless you have specified a ``seed value'' as explained in Chapter~xx).
\begindemo
\it\kern-2pt You type&\it\kern-1pt And the result might be\cr
\noalign{\vskip2pt}
uniformdeviate 100&47.4241\cr
uniformdeviate 100&97.28148\cr
uniformdeviate 100&36.16279\cr
(normaldeviate,normaldeviate)&(0.46236,-1.87648)\cr
\enddemo
The value of `uniformdeviate\thinspace100' is a random number between 0 and~100;
↑↑{uniformdeviate} ↑↑{normaldeviate}
the value of `normaldeviate' is a normally distributed random number whose
mean value is zero and whose standard deviation is unity. Chapter~xx explains
what this means and gives several applications.

\danger Besides all of these operations on numbers, \MF\ has a rich collection
↑↑{scaled} ↑↑{xscaled} ↑↑{yscaled} ↑↑{dir}
of operations on pairs, some of which are indicated in the following examples:
\begindemo
\demohead
right&(1,0)\cr
(1,2)+(3,4)&(4,6)\cr
1/3(3,10)&(1,3.33333)\cr
z1-z2&(x1-x2,y1-y2)\cr
.2[z1,z2]&(0.8x1+0.2x2,0.8y1+0.2y2)\cr
3z&(3x,3y)\cr
z scaled 3&(3x,3y)\cr
z xscaled 2 yscaled 1/2&(2x,0.5y)\cr
z shifted (2,3)&(x+2,y+3)\cr
z shifted 3right&(x+3,y)\cr
z slanted 1/6&(x+0.16667y,y)\cr
z rotated 90&(-y,x)\cr
z rotated 30&(0.86603x-0.5y,0.5x+0.86603y)\cr
xpart(z rotated 30)&0.86603x-0.5y\cr
ypart(z rotated 30)&0.5x+0.86603y\cr
(1,2)*(3,4)&(3,4)\werror\cr
(1,2)zscaled(3,4)&(-5,10)\cr
(a,b)zscaled(3,4)&(3a-4b,4a+3b)\cr
(a,b)zscaled dir 30&(0.86603a-0.5b,0.5a+0.86603b)\cr
(1,2)dotprod(3,4)&11\cr
(a,b)dotprod(3,4)&3a+4b\cr
dir 21 dotprod dir 51&0.86603\cr
(3,4)dotprod((30,40)rotated 90)&0\cr
\enddemo
(Recall that plain \MF\ converts `|z$|' into `|(x$,y$)|' when |$| is any
\<suffix>.) \  ↑↑{xpart} ↑↑{ypart} ↑↑{shifted} ↑↑"right" ↑↑{slanted}
↑↑{zscaled} ↑↑{dotprod} ↑↑"z" The operations exhibited here are almost
all self-evident. When a point or vector is ↑{rotated}, it is moved
counterclockwise about $(0,0)$ through a given number
of degrees. \MF\ computes the rotated coordinates by using
↑{sines} and ↑{cosines} in an appropriate way; you don't have to
remember the formulas! Although you cannot use `|*|' to multiply
a pair by a pair, you can use `↑{zscaled}' to get the effect of
↑{complex number} multiplication: Since $(1+2i)$ times $(3+4i)$ is
$-5+10i$, we have $(1,2)\mathbin{\rm zscaled}(3,4)=(-5,10)$.
There's also a ↑{multiplication} that converts pairs into numbers:
$(a,b)\mathbin{\rm dotprod}(c,d\mkern1mu)=ac+bd$. This is the
``↑{dot product},'' often written `$(a,b)\cdot(c,d\mkern1mu)$' in
mathematics texts; it turns out to be equal to $a\pyth+b$ times
$c\pyth+d$ times the cosine of the angle between the vectors $(a,b)$ and
$(c,d)$. Since cosd$\,90↑\circ=0$, two vectors are
↑{perpendicular} to each other if and only if their dot ↑{product} is zero.

\danger There are operations on strings, paths, and the other types too;
we shall study such things carefully in later chapters. For now, it will
suffice to give a few examples, keeping in mind that the file |expr.mf|
defines |s| with any subscript to be a ↑{string}, while |p| with any subscript
is a path. Furthermore $s↓1$ has been given the value |"abra"|, while
$p↓1$ is `$(0,0)\to(3,3)$' and $p↓2$ is `$(0,0)\to(3,3)\to"cycle"$'.
\begindemo
\demohead
s2&unknown string s2\cr
s1\&"cad"\&s1&"abracadabra"\cr
length s1&4\cr
length p1&1\cr
length p2&2\cr
cycle p1&false\cr
cycle p2&true\cr
substring (0,2) of s1&"ab"\cr
substring (2,infinity) of s1&"ra"\cr
point 0 of p1&(0,0)\cr
point 1 of p1&(3,3)\cr
point .5 of p1&(1.5,1.5)\cr
point infinity of p1&(3,3)\cr
point .5 of p2&(3,0)\cr
point 1.5 of p2&(0,3)\cr
point 2 of p2&(0,0)\cr
point 2+epsilon of p2&(0.00009,-0.00009)\cr
point -epsilon of p2&(-0.00009,0.00009)\cr
point -1 of p1&(0,0)\cr
direction 0 of p1&(1,1)\cr
direction 0 of p2&(4,-4)\cr
direction 1 of p2&(-4,4)\cr
\enddemo
↑↑{point} ↑↑{direction}
The ↑{length} of a path is the number of `$\to$' steps that it contains;
the construction `↑|cycle|~\<path>' can be used to tell whether or not a
particular path is cyclic.  If you say just `|p1|' you get to see
path~$p↓1$ with its ↑{control points}:
\begintt
(0,0)..controls (1,1) and (2,2)
 ..(3,3)
\endtt
Similarly, `|p2|' is
\begintt
(0,0)..controls (2,-2) and (5,1)
 ..(3,3)..controls (1,5) and (-2,2)
 ..cycle
\endtt
and `|subpath| |(0,1)| |of| |p2|' is analogous to a ↑{substring}:↑↑{subpath}
\begintt
(0,0)..controls (2,-2) and (5,1)
 ..(3,3)
\endtt
The expression `point $t$ of $p↓2$' gives the position of a point that
moves along path~$p↓2$, starting with the initial point $(0,0)$ at $t=0$,
then reaching point $(3,3)$ at $t=1$, etc.;
 the value at $t=1/2$ is the
third-order midpoint obtained by the construction of Chapter~3, using
intermediate control points $(2,-2)$ and $(5,1)$.
Since $p↓2$ is a cyclic path of length~2,
point $(t+2)$ of~$p↓2$ is the same as point~$t$. Path $p↓1$ is not
cyclic, so its points turn out to be identical to point~0 when $t<0$,
and identical to point~1 when $t>1$. The expression `direction~$t$
of~\<path>' is similar to `point~$t$ of \<path>'; it yields a vector for the
direction of travel at time~$t$.

{\ninepoint
\medbreak
\parshape 14 3pc 12pc 3pc 12pc
0pc 15pc 0pc 15pc 0pc 15pc 0pc 15pc 0pc 15pc 0pc 15pc
0pc 15pc 0pc 15pc 0pc 15pc 0pc 15pc 0pc 15pc 0pc 29pc
\noindent
\hbox to0pt{\hskip-3pc\dbend\hfill}
\rightfig 8a (12pc x 12pc) ↑16pt
Paths are not necessarily traversed at constant speed. For example,
the diagram at the right shows point $t$ of~$p↓2$ at twenty equally
spaced values of~$t$.
\MF\ moves faster in this case at time 0 than at time 0.2; but the points are
spread out fairly well, so the concept of fractional
time can be useful. The diagram shows, incidentally, that
path~$p↓2$ is not an especially good approximation to
a circle; there is no left-right symmetry, although the curve from point~1
to point~2 is a mirror image of the curve from point~0 to point~1.
This lack of circularity is not surprising, since
$p↓2$ was defined by simply specifying two points, $(0,0)$ and~$(3,3)$;
at least four points are needed to get a path that is convincingly round.
\parfillskip=0pt\par}

\ddanger The ↑{ampersand} operation `|&|' can be used to splice paths
together in much the same way as it concatenates strings. For example, if
you type `|p2|~|&|~|p1|', you get the path of length~3 that is obtained by
breaking the cyclic connection at the end of path~$p↓2$ and attaching~$p↓1$:
\begintt
(0,0)..controls (2,-2) and (5,1)
 ..(3,3)..controls (1,5) and (-2,2)
 ..(0,0)..controls (1,1) and (2,2)
 ..(3,3)
\endtt
Concatenated paths must have identical endpoints at the junction.

\ddanger You can even ``slow down the clock'' by concatenating subpaths
that have non-integer time specifications. For example, here's what you
get if you ask for `|subpath|~|(0,.5)| |of|~|p2| |&| |subpath| |(.5,2)|
|of|~|p2| |&| |cycle|':
\begintt
(0,0)..controls (1,-1) and (2.25,-0.75)
 ..(3,0)..controls (3.75,0.75) and (4,2)
 ..(3,3)..controls (1,5) and (-2,2)
 ..cycle
\endtt
When $t$ goes from 0 to 1 in subpath $(0,.5)$ of $p↓2$, you get the same
points as when $t$ goes from 0 to~.5 in $p↓2$; when $t$ goes from 0 to 1
in subpath $(.5,2)$ of~$p↓2$, you get the same points as when $t$ goes
from .5 to~1 in~$p↓2$; but when $t$ goes from 1 to~2 in subpath
$(.5,2)$ of~$p↓2$, it's the same as the segment from 1 to~2 in~$p↓2$.

\danger Let's conclude this chapter by discussing the exact rules of
↑{precedence} by which \MF\ decides what operations to do first. The
informal notion of ``magnetism'' gives a good intuitive picture of what
happens, but syntax rules express things unambiguously in borderline cases.

\danger The four levels of precedence correspond to four kinds of formulas,
which are called primaries, secondaries, tertiaries, and
expressions. A {\sl↑{primary}\/} is a~variable or a constant or a
tightly bound unit like `|2x|' or `|sqrt 2|'; a {\sl↑{secondary}\/}
is~a primary or a sequence of primaries connected by multiplicative
operators like `|*|' or `|scaled|'; a {\sl↑{tertiary}\/} is a secondary
or a sequence of secondaries connected by additive operators like `|+|'
or `|++|'; an {\sl↑{expression}\/} is a tertiary or a sequence of
tertiaries connected by external operators like `|<|' or `|..|'. For example,
the expression
\begintt
a+b/2>3c*sqrt4d
\endtt
is composed of the primaries `|a|', `|b|', `|2|', `|3c|', and `|sqrt4d|';
the last of these is a primary containing `|4d|' as a primary within itself.
The subformulas `|a|', `|b/2|', and `|3c*sqrt4d|' are secondaries; the
subformulas `|a+b/2|' and `|3c*sqrt4d|' are tertiaries.

\danger If an expression is enclosed in parentheses, it becomes a primary
that can be used to build up larger secondaries, tertiaries, etc.

\danger The full syntax for expressions is quite long, but most of it
falls into a simple pattern. If $\alpha$, $\beta$, and~$\gamma$ are
any ``types''---numeric, boolean, string, etc.---then \<$\alpha$ variable>
refers to a variable of type~$\alpha$, \<$\beta$ primary> refers to a
primary of type~$\beta$, and so on. Almost all of the syntax rules fit into
the following general framework:
\beginsyntax
<$\alpha$ primary>\is<$\alpha$ variable>\alt<$\alpha$ constant>%
 \alt[(]<$\alpha$ expression>[)]
 \alt<operator that takes type $\beta$ to type $\alpha$><$\beta$ primary>
<$\alpha$ secondary>\is\<$\alpha$ primary>
 \alt<$\beta$ secondary><multiplicative op taking types $\beta$ and %
 $\gamma$ to $\alpha$><$\gamma$ primary>\kern-1pt
<$\alpha$ tertiary>\is\<$\alpha$ secondary>
 \alt<$\beta$ tertiary><additive op taking types $\beta$ and %
 $\gamma$ to $\alpha$><$\gamma$ secondary>
<$\alpha$ expression>\is<$\alpha$ tertiary>
 \alt<$\beta$ expression><external op taking types $\beta$ and %
 $\gamma$ to $\alpha$><$\gamma$ tertiary>
\endsyntax
These schematic rules don't give the whole story, but they do give the
general structure of the plot.

\danger Chapter xx spells out all of the syntax rules for all types of
expressions. We shall consider only a portion of the numeric and pair
cases here, in order to have a foretaste of the complete menu:
\def\\#1{\thinspace{\tt#1}\thinspace}
\beginsyntax
<numeric primary>\is<numeric variable>
 \alt<numeric token primary>
 \alt[(]<numeric expression>[)]
 \alt[length]<string primary>
 \alt[length]<path primary>
 \alt[length]<pair primary>
 \alt[angle]<pair primary>
 \alt[xpart]<pair primary>
 \alt[ypart]<pair primary>
 \alt<numeric operator><numeric primary>
 \alt[normaldeviate]
<numeric operator>\is[sqrt]\alt[sind]\alt[cosd]\alt[mlog]\alt[mexp]
 \alt[floor]\alt[uniformdeviate]
 \alt<scalar multiplication operator>
<scalar multiplication operator>\is<plus or minus>
 \alt<numeric token primary not followed by %
  {\tt+} or {\tt-} or a numeric token>
<numeric token primary>\is<numeric token>[/]<numeric token>
 \alt<numeric token not followed by %
  `{\tt/}$\thinspace\langle$numeric token$\rangle$'\thinspace>
<numeric secondary>\is<numeric primary>
 \alt<numeric secondary><times or over><numeric primary>
 \alt<numeric secondary>\\{\char`\[}%
  <numeric expression>[,]<numeric expression>\\{\char`\]}
<times or over>\is[*]\alt[/]
<numeric tertiary>\is<numeric secondary>
 \alt<numeric tertiary><plus or minus><numeric secondary>
 \alt<numeric tertiary><Pythagorean plus or minus><numeric secondary>
<plus or minus>\is[+]\alt[-]
<Pythagorean plus or minus>\is[++]\alt[+-+]
<numeric expression>\is<numeric tertiary>
\endsyntax
All of the finicky details about ↑{fractions} and such things are made
explicit by this syntax. For example, we can use the rules to deduce that
`|sind-1/3x-2|' is interpreted as `|(sind(-(1/3x)))-2|'; notice that the
first minus sign in this formula is considered to be a ``scalar multiplication
operator,'' which comes in at the primary level, while the second one denotes
subtraction and enters in the construction of \<numeric tertiary>. The
↑{mediation} or ``↑{of-the-way}'' operation `$t[a,b]$' is handled at the
secondary level.

\danger Several operations that haven't been discussed yet do not appear
in the syntax above, but they fit into the same general pattern; for example,
we will see later that `↑|ASCII|\<string primary>' and `↑|xxpart|\<transform
primary>' are additional cases of the syntax for \<numeric primary>.
On the other hand, several operations that we have discussed in this chapter
do not appear in the syntax, because they are not primitives of \MF\ itself;
they are defined in the plain \MF\ base (Appendix B\null). For example,
`↑|ceiling|' is analogous to `|floor|', and `↑|**|' is analogous to~`|*|'.
Chapter~xx explains how \MF\ allows extensions to its built-in syntax,
so that additional operations can be added at will.

\dangerexercise How does \MF\ interpret `|2|~|2|'\thinspace?
\ (There's a space between the 2's.)
\answer It's impossible to make an expression from `\<numeric token>
\<numeric token>', because the rule for \<scalar multiplication operator>
specifically prohibits this. \MF\ will recognize the first `|2|' as
a \<numeric primary>, which is ultimately regarded as a \<numeric
expression>; the other `|2|' will probably be an extra token that is
flushed away after an error message has been given.

\danger The rules of \<pair expression> are similar to those for
\<numeric expression>, so it's convenient to learn them both at the same time.
\beginsyntax
<pair primary>\is<pair variable>
 \alt[(]<numeric expression>[,]<numeric expression>[)]
 \alt[(]<pair expression>[)]
 \alt[point]<numeric expression>[of]<path primary>
 \alt<scalar multiplication operator><pair primary>
<pair secondary>\is<pair primary>
 \alt<pair secondary><times or over><numeric primary>
 \alt<numeric secondary>[*]<pair primary>
 \alt<numeric secondary>\\{\char`\[}%
  <pair expression>[,]<pair expression>\\{\char`\]}
 \alt<pair secondary><transformer>
<transformer>\is[rotated]<numeric primary>
 \alt[slanted]<numeric primary>
 \alt[scaled]<numeric primary>
 \alt[shifted]<pair primary>
 \alt[transformed]<transform primary>
 \alt[xscaled]<numeric primary>
 \alt[yscaled]<numeric primary>
 \alt[zscaled]<pair primary>
<pair tertiary>\is<pair secondary>
 \alt<pair tertiary><plus or minus><pair secondary>
<pair expression>\is<pair tertiary>
\endsyntax

\dangerexercise Try to guess the syntax rules for \<string primary>,
\<string secondary>, $\langle$string tertiary$\rangle$, and \<string
expression>, based solely on the examples that have appeared in this
chapter.  \ [{\sl Hint:}\/ The `|&|' operation has the same precedence
as `|..|'.]
\answer \<string primary>\is\<string variable>\parbreak
\qquad\alt\<string token>\parbreak
\def\\#1{\thinspace{\tt#1}\thinspace}%
\qquad\alt\\(\<string expression>\\)\parbreak
\qquad\alt\\{substring}\<pair expression>\\{of}\<string primary>\parbreak
\<string secondary>\is\<string primary>\parbreak
\<string tertiary>\is\<string secondary>\parbreak
\<string expression>\is\<string tertiary>\parbreak
\qquad\alt\<string expression>\\{\char`\&}\<string tertiary>\par
\medskip\noindent
(The full syntax in Chapter~xx includes several more varieties of
\<string primary> that haven't been hinted at yet.)

\endchapter

A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Chapter 9. Equations

The variables in a \MF\ program receive their values by appearing in
{\sl↑{equations}}, which express relationships that the programmer
wants to achieve. We've seen in the previous chapter that algebraic
expressions provide a rich language for dealing with both numerical
and graphical relationships. Thus it is possible to express a great
variety of design objectives in precise form by stating that certain
algebraic expressions should be equal to each other.

The most important things a \MF\ programmer needs to know about
equations are (1)~how to translate intuitive design concepts into
formal equations, and (2)~how to translate formal equations into
intuitive design concepts. In other words, it's important to be able
to {\sl write\/} equations, and it's also important to be able to
{\sl read\/} equations that you or somebody else has written. This
is not nearly as difficult as it might seem at first. The best way
to learn~(1) is to get a lot of practice with~(2) and to generalize
from specific examples. Therefore we shall begin this chapter by
translating a lot of equations into ``simple English.''

\newdimen\longesteq
\setbox0=\hbox{\indent$z↓{12}-z↓{11}=z↓{14}-z↓{13}$\quad}
\longesteq=\wd0
\def\\#1\\{\medbreak\noindent
  \hbox to\longesteq{\indent#1\hfil}%
  \hangindent\longesteq\ignorespaces}
\medskip
\noindent\hbox to\longesteq{\indent\kern-1pt\sl Equation\hfil}%
\kern-1pt{\sl Translation}\smallskip

\\$a=3.14$\\
The value of $a$ should be 3.14.

\\$3.14=a$\\
The number 3.14 should be the value of $a$. \ (This means the same
thing as `$a=3.14$'; the left and right sides of an equation can be
interchanged without affecting the meaning of that equation in any way.)

\\$"mode"="smoke"$\\
The value of ↑"mode" should be equal to the value of ↑"smoke". \
(Plain \MF\ assigns a special meaning to `"smoke"', so that if
↑@mode\_setup@ is invoked when $"mode"="smoke"$ the computer will
prepare ``smoke proofs'' as explained in Chapter~5 and Appendix~H.)

\\$y↓3=0$\\
The $y$ coordinate of point 3 should be zero; i.e., point~3 should
be at the ↑{baseline}. \ (Point~3 is also known as~$z↓3$, which is an
abbreviation for the pair of coordinates $(x↓3,y↓3)$, if you are
using the conventions of plain \MF.)

\\$x↓9=0$\\
The $x$ coordinate of point 9 should be zero; i.e., point~9 should
be at the left edge of the type box that encloses the current character.

\\$x↓{1l}="curve\_sidebar"$\\
The $x$ coordinate of point $1l$ should be equal to the value of the
variable called "curve\_sidebar". This puts $z↓{1l}$ a certain
distance from the left edge~of the type.

\\$x↓1=x↓2$\\
Points 1 and 2 should have the same $x$ coordinate; i.e., they should
have the same horizontal position, so that one will lie directly
above or below the other.

\\$y↓4=y↓5+1$\\
Point 4 should be one pixel higher than point~5.
\ (However, points 4 and~5 might be far apart; this equation
says nothing about the relation between $x↓4$ and~$x↓5$.)

\\$y↓6=y↓7+2"mm"$\\
Point 6 should be two millimeters higher than point~7. \ (Plain \MF's
↑@mode\_setup@ routine sets variable ↑"mm" to the number of pixels in a
millimeter, based on the resolution determined by "mode" and "mag".)

\\$x↓4=w-.01"in"$\\
Point 3 should be one-hundredth of an inch inside the right edge of
the type. \ (Plain \MF's ↑@beginchar@ routine sets variable~↑"w" equal
to the width of whatever character is currently being drawn, expressed in
pixels.)

\\$y↓4=.5h$\\
Point 4 should be halfway between the baseline and the top of the type.
\ (Plain \MF's @beginchar@ sets ↑"h" to the height of the
current character, in pixels.)

\\$y↓6=-d$\\
Point 6 should be below the baseline, at the bottom edge of the type.
\ (Each character has a ``↑{bounding box}'' that runs from $(0,h)$
at the upper left and $(w,h)$ at the upper right to $(0,-d)$ and~$(w,-d)$
at the lower left and lower right; variable~↑"d" represents the depth of
the type. The values of $w$, $h$, and~$d$ might change from character to
character, since the individual pieces of type in a computer-produced
font need not have the same size.)

\\$y↓8=.5[h,-d]$\\
Point 8 should be halfway between the top and bottom edges of the type.

\\$w-x↓5={2\over3}x↓6$\\
The distance from point 5 to the right edge of the type should be
two-thirds of the distance from point~6 to the left edge of the~type.
\ (Since $w$ is at the right edge, $w-x↓5$ is the ↑{distance} from
point~5 to the right edge.)

\\$z↓0=(0,0)$\\
Point 0 should be at the ↑{reference point} of the current character,
i.e., it should be on the baseline at the left edge of the type.
This equation is an abbreviation for two equations, `$x↓0=0$' and `$y↓0=0$',
because an equation between pairs of coordinates implies that the $x$
and~$y$ coordinates must both agree. \ (Incidentally, plain \MF\
defines a variable called ↑"origin" whose value is $(0,0)$; hence
this equation could also have been written `$z↓0="origin"$'.)

\\$z↓9=(w,h)$\\
Point 9 should be at the upper right corner of the current character's
bounding box.

\\$"top"\,z↓8=(.5w,h)$\\
If the pen that has currently been ``picked up'' is placed at point~8,
its top edge should be at the top edge of the type. Furthermore,
$x↓8$~should be $.5w$; i.e., point~8 should be centered between the
left and right edges of the type. \ (Chapter~4 contains further
examples of `↑"top"', as well as the corresponding operations
`"bot"', `"lft"', and `"rt"'.)

\\$z↓4={3\over7}[z↓5,z↓6]$\\
Point 4 should be three-sevenths of the way from point~5 to  point~6.

\\$z↓{12}-z↓{11}=z↓{14}-z↓{13}$\\
The ↑{vector} that moves from point 11 to point~12 should be the same
as the vector that moves from point~13 to point~14. In other words,
point~12 should have the same direction and distance from point~11
as point~14 has from point~13.

\\\smash{\vtop{\hbox{$z↓3-z↓2=$}
  \hbox{\quad$(z↓4\!-\!z↓2)$\thinspace rotated\thinspace 15}}}\\
Points 3 and 4 should be at the same distance from point~2, but
the direction to point~3 should be 15~degrees counterclockwise from
the direction to point~4.

\exercise Translate the following equations into ``simple English'':
\ (a)~$x↓7-9=x↓1$; \ (b)~$z↓7=(x↓4,.5[y↓4,y↓5])$; \ 
(c)~$"lft"\,z↓{21}="rt"\,z↓{20}+1$.
\answer (a)~Point 1 should lie nine pixels to the left of point~7,
considering horizontal positions only; no information is given about the
vertical positions $y↓1$ or $y↓7$. \ (b)~Point~7 should sit directly
above or below point~4, and its distance up from the baseline should be
halfway between that of points 4 and~5. \ (c)~The left edge of the
currently-picked-up pen, when that pen is centered at point~21, should be
one pixel to the right of its right edge when at point~20. \ (Thus there
should be one clear pixel of white space between the images of the
pen at points 20 and~21.)

\exercise Now see if your knowledge of equation reading gives you the
ability to write equations that correspond to the following objectives:
\ (a)~Point~13 should be just as far below the baseline as point~11 is
above the baseline. \ (b)~Point~10 should be one millimeter to the right
of, and one pixel below, point~12. \ (c)~Point~43 should be one-third of
the way from the top left corner of the type to the bottom right corner
of the type.
\answer (a) $y↓{13}=-y↓{11}$ (or $-y↓{13}=y↓{11}$, or $y↓{13}+y↓{11}=0$).
\ (b)~$z↓{10}=z↓{12}+("mm",-1)$. \ (c)~$z↓{43}={1\over3}[(0,h),(w,-d)]$.

Let's return now to the six example points $(z↓1,z↓2,z↓3,z↓4,z↓5,z↓6)$
that were used so often in Chapters 2 and~3. Changing the notation
slightly, we might say that the points are
\begindisplay
$(x↓1,y↓1)=(0,h)$;&$(x↓2,y↓2)=(.5w,h)$;&$(x↓3,y↓3)=(w,h)$;\cr
$(x↓4,y↓4)=(0,0)$;&$(x↓5,y↓5)=(.5w,0)$;&$(x↓6,y↓6)=(w,0)$.\cr
\enddisplay
There are many ways to specify these points by writing a series of
equations. For example, the six equations just given would do fine;
or the short names $z↓1$ through~$z↓6$ could be used instead of the
long names $(x↓1,y↓1)$ through~$(x↓6,y↓6)$. But there are several
other ways to specify those points and at the same time to ``explain''
the relations they have to each other. One way is to define the
$x$ and~$y$ coordinates separately:
\begindisplay
$x↓1=x↓4=0;\qquad x↓2=x↓5=.5w;\qquad x↓3=x↓6=w;$\cr
$y↓1=y↓2=y↓3=h;\qquad y↓4=y↓5=y↓6=0$.\cr
\enddisplay
\MF\ allows you to state several equations at once, by using more than
↑↑{=} one equality sign; for example, `$y↓1=y↓2=y↓3=h$' stands for three
equations, `$y↓1=y↓2$', `$y↓2=y↓3$', and `$y↓3=h$'.

In order to define the coordinates of six points, it's necessary to
write twelve equations, because each equation contributes to the
definition of one value, and because six points have twelve coordinates
in all. However, an equation between pairs of coordinates counts as
two equations between single numbers; that's why we were able to get by
with only six `$=$'~signs in the first set of equations, while twelve
were used in the second.

Let's look at yet another way to specify those six points, by giving
equations for their positions relative to each other:
\begindisplay
$z↓1-z↓4=z↓2-z↓5=z↓3-z↓6$\cr
$z↓2-z↓1=z↓3-z↓2=z↓5-z↓4=z↓6-z↓5$\cr
$z↓4="origin"$; \ $z↓3=(w,h)$.\cr
\enddisplay
↑↑"origin" First we say that the vectors from $z↓4$ to~$z↓1$,
from $z↓5$ to~$z↓2$, and from $z↓6$ to~$z↓3$, are equal to each other;
then we say the same thing for the vectors from $z↓1$ to~$z↓2$,
$z↓2$ to~$z↓3$, $z↓4$ to~$z↓5$, and $z↓5$ to~$z↓6$. Finally the
corner points $z↓4$ and $z↓3$ are given explicitly. That's a total
of seven equations between pairs of coordinates, so it should be
more than enough to define the six points of interest.

However, it turns out that those seven equations are not enough!
For example, the six points
\begindisplay
$z↓1=z↓4=(0,0)$; \ $z↓2=z↓5=(.5w,.5h)$; \ $z↓3=z↓6=(w,h)$
\enddisplay
also satisfy the same equations. A closer look explains why:
The two formulas
\begindisplay
$z↓1-z↓4=z↓2-z↓5$\qquad and\qquad $z↓2-z↓1=z↓5-z↓4$
\enddisplay
actually say exactly the same thing. \ (Add $z↓5-z↓1$ to both sides
of the first equation and you get `$z↓5-z↓4=z↓2-z↓1$'.) \ Similarly,
$z↓2-z↓5=z↓3-z↓6$ is the same as $z↓3-z↓2=z↓6-z↓5$. Two of the
seven equations give no new information, so we really have specified
only five equations; that isn't enough. An additional relation
such as `$z↓1=(0,h)$' is needed to make the solution unique.

\dangerexercise (For mathematicians.) \ Find a solution to the seven
equations such that $z↓1=z↓2$. Also find another solution in which
$z↓1=z↓6$.
\answer (a) $z↓1=z↓2=z↓3=(w,h)$; $z↓4=z↓5=z↓6=(0,0)$.
\ (b)~$z↓1=z↓6=(.5w,.5h)$; $z↓2=(.75w,.75h)$; $z↓3=(w,h)$;
$z↓4=(0,0)$; $z↓5=(.25w,.25h)$.

At the beginning of a \MF\ program, variables have no values,
except that plain \MF\ has assigned special values to variables
like "smoke" and "origin". Furthermore, when you begin a new
character with @beginchar@, any previous values that may have been
assigned to $x$ or $y$ variables are obliterated and forgotten.
Values are gradually established as the computer reads equations and
tries to solve them, together with any other equations that have already
appeared in the program.

It takes ten equations to define the values of ten variables.
If you have given only nine equations it may turn out that none of
the ten variables has yet been determined; for example, the
nine equations
\begindisplay
$g↓0=g↓1=g↓2=g↓3=g↓4=g↓5=g↓6=g↓7=g↓8=g↓9$
\enddisplay
don't tell us any of the $g$ values. However, the further equation
\begindisplay
$g↓0+g↓1=1$
\enddisplay
will cause \MF\ to deduce that all ten of the $g$'s are equal to $1\over2$.

\MF\ always computes the values of as many variables as possible, based
on the equations it has seen so far. For example, after the two equations
\begindisplay
$a+b+2c=3$;\cr
$a-b-2c=1$\cr
\enddisplay
the machine will know that $a=2$ (because the sum of these two equations is
`$2a=4$'); but all it will know about $b$ and~$c$ is that $b+2c=1$.

At any point in a program a variable is said to be either ``↑{known}''
or ``↑{unknown},'' depending on whether or not its value can be
deduced uniquely from the equations that have been stated so far.
The sample expressions in Chapter~8 indicate that \MF\ can compute a
variety of things with unknown variables; but sometimes a quantity
must be known before it can be used. For example, \MF\ can multiply
an unknown numeric or pair variable by a known numeric value, but it
cannot multiply two unknowns.

Equations can be given in any order, except that you might sometimes
need to put certain equations first in order to make critical
values known in the others. For example, \MF\ will find the
solution $(a,b,c)=(2,7,-3)$ to the equations `$a+b+2c=3$;
$a-b-2c=1$; $b+c=4$' if you give those equations in any other order,
like `$b+c=4$; $a-b-2c=1$; $a+b+2c=3$'. But if the equations had
been `$a+b+2c=3$; $a-b-2c=1$; $a\ast(b+c)=8$', you would not have
been able to give the last one first, because \MF\ would have refused
to multiply the unknown quantity~$a$ by another unknown quantity $b+c$.
Here are the main things that \MF\ can do with unknown quantities:
\begindisplay
$-\<unknown>$\cr
$\<unknown>+\<unknown>$\cr
$\<unknown>-\<unknown>$\cr
$\<unknown>\ast\<known>$\cr
$\<known>\ast\<unknown>$\cr
$\<unknown>/\<known>$\cr
$\<known>[\<unknown>,\<unknown>]$\cr
$\<unknown>[\<known>,\<known>]$\cr
\enddisplay
Some of the operations of plain \MF\!, defined in Appendix~B, also work
with unknown quantities. For example, it's possible to say
↑"top"\thinspace\<unknown>, ↑"bot"\thinspace\<unknown>,
↑"lft"\thinspace\<unknown>, ↑"rt"\thinspace\<unknown>, and even
\begindisplay
@penpos@\<suffix>(\<unknown>,\thinspace\<known>).
\enddisplay

\danger A \MF\ program can say `\<unknown>$[a,b\mkern1mu]$' when $a-b$ is
known, and variable~$a$ can be compared to variable~$b$ in boolean
expressions ↑↑{comparison} like `$a<b$' when $a-b$ is known. The quantity
$a-b$ might be known even when $a$ and~$b$ aren't known by themselves.

\danger You might wonder how \MF\ is able to keep its knowledge up-to-date,
based on scraps of  partial information that it receives from miscellaneous
equations. The best way to understand this is to watch how it happens,
by asking the computer to show certain calculations that it usually keeps
to itself. Here's one way to do it: Run \MF\ and say
\begintt
\tracingequations:=tracingonline:=1;
\endtt
↑↑"tracingequations" ↑↑"tracingonline"
in response to the opening `|**|'. \ (Be sure to type the backslash `|\|',
and to use `|:=|' instead of `|=|'. We will see in Chapter~27 that \MF\
can be asked to ``trace'' many aspects of what it's doing.) \ Now type
\begintt
a+b+2c=3;
\endtt
the machine will reply by saying
\begintt
## c=-0.5b-0.5a+1.5
\endtt
since that is how it has digested your equation. \ (The `|##|' in this
↑↑{hash hash} line identifies diagnostic information that comes from
"tracingequations".) \ Now type
\begintt
a-b-2c=1;
\endtt
\MF\ will read this as if you had said `|a-b-2(-0.5b-0.5a+1.5)=1|',
since it has previously learned how to replace |c| by an expression
that involves only |a| and~|b|. This new equation can be simplified by
multiplying out the left-hand side and collecting terms. The result is
`|2a-3=1|', hence \MF\ will respond with
\begintt
## a=2
\endtt
and it will be your turn to type something again. Say
\begintt
showdependencies;
\endtt
↑↑@showdependencies@ \MF's response will be
\begintt
c=-0.5b+0.5
\endtt
indicating that there is only one variable whose value depends on others,
and its equation of dependency is now `$c=-0.5b+0.5$'. \ (The previous
dependency equation `$c=-0.5b-0.5a+1.5$' has
been simplified to take account of the newly discovered value, $a=2$.) \
Finally type
\begintt
b+c=4;
\endtt
this spurs the computer on to say
\begintt
## b=7
#### c=-3
\endtt
A line that begins with `|##|' states what \MF\ has deduced from
the equation it has just read; a line that begins with `|####|' states
↑↑{hash hash hash hash} an indirect consequence of that direct result,
if some previously dependent variable has now become known.

\danger It's interesting to continue the computer experiment just begun
by typing the following lines, one at a time, and watching what happens:
\begintt
a'+b'+.5c'=3;
a'-b'-.5c'=1;
g0=g1=g2=g3=g4;
showdependencies;
g0+g1=1;
z1-z4=z2-z5=z3-z6;
z2-z1=z3-z2=z5-z4=z6-z5;
z4=origin;
z3=(w,h);
x1=0;
y6=0;
w=2h=100;
end.
\endtt
Notice that on the sixth line (\thinspace`$z↓1-z↓4=\cdots\,$'\thinspace)
\MF\ reports four equations, but on the next line
(\thinspace`$z↓2-z↓1=\cdots\,$'\thinspace) it reports only two.  This
happens because most of that line is redundant, as we have already
observed.

\danger This computer session indicates that \MF\ deals with two kinds
of unknown numeric variables: {\sl↑{dependent}\/} variables and
{\sl↑{independent}} ones.
Every variable is independent at the beginning of its life, but every
equation causes one of the independent variables to become dependent
or ↑{known}. Each `|##|' line emitted by "tracingequations" shows a
newly dependent-or-known variable, together with an equivalent expression
that involves only independent variables. For example, the line
`|##|~|c=-0.5b-0.5a+1.5|'
means that variable~$c$ has just become dependent and that it equals
$-{1\over2}b-{1\over2}a+1.5$, where variables $b$ and~$a$ are independent.
Similarly, `|##|~|a=2|' means that $a$~has just changed from
independent to known. When an independent variable~$v$ changes to dependent
or known, the equivalents of all dependent variables are updated so that
they no longer depend on~$v$; in this updating process some or all of them
may change from dependent to known, whereupon a `|####|' line will be printed.

\ddanger When \MF\ reads a numeric equation it replaces all known variables
by their numeric values and all dependent variables by their equivalents.
The resulting equation can be converted into the form
\begindisplay
$c↓1v↓1+\cdots+c↓mv↓m=\alpha$
\enddisplay
where the $c$'s are nonzero constants and the $v$'s are independent variables;
$\alpha$~is a numeric constant that might be zero. If some $c↓k$ is so
small that it probably would have been zero in a calculation free of
rounding errors, it is replaced by zero and the corresponding $v↓k$ is
removed from the equation. Now if $m=0$, the equation is considered to be
either {\sl↑{redundant}\/} (if $\alpha$ is zero or extremely small)
or {\sl↑{inconsistent}\/} (otherwise). But if $m>0$, \MF\ chooses an
independent variable~$v↓k$ for which $c↓k$ is maximum, and rewrites
the equation in the form
\begindisplay
{\tt\#\#} $v↓k=(\alpha-c↓1v↓1-\cdots-c↓{k-1}v↓{k-1}-c↓{k+1}v↓{k+1}-
 \cdots-c↓mv↓m)/c↓k$.
\enddisplay
Variable $v↓k$ becomes dependent (if $m>1$) or known (if $m=1$).

\danger Inconsistent equations are equations that have no solutions.
For example, if you say `$0=1$', \MF\ will issue an error message
↑↑{off by x}
saying that the equation is ``off by~1.'' A less blatant inconsistency
arises if you say, e.g, `$a=b+1$; $b=c+1$; $c=a+1$'; this last equation
is off by three, for the former equations imply that $c=b-1=a-2$.
The computer will simply ignore an inconsistent equation when you
resume processing after such an error.

\danger Redundant equations are equations that say nothing new.
For example, `$0=0$' is redundant, and so is `$a=b+c$' if you have
previously said that $c=a-b$. \MF\ stops with an error message if
you give it a redundant equation between two numeric expressions,
because this usually indicates an oversight in the program. However,
no error is reported when an equation between pairs leads to one or
two redundant equations between numerics. For example, the equation
`$z↓3=(0,h)$' will not trigger an error message when the program
has previously established that $x↓3=0$ or that $y↓3=h$ or both.

\danger Sometimes you might have to work a little bit to put an equation
into a form that \MF\ can handle. For example, you can't say
\begindisplay
$x/y=2$
\enddisplay
when $y$ is independent or dependent, because \MF\ allows ↑{division}
only by known quantities. The alternative
\begindisplay
$x=2y$
\enddisplay
says the same thing and causes the computer no difficulties;
furthermore it is a correct equation even when $y=0$.

\ddanger \MF's ability to remember previous equations is limited to
``linear'' dependencies ↑↑{linear dependencies} as explained above.
A mathematician might want to introduce the condition $x\ge0$ by giving an
equation such as `$x=\mathop{\rm abs}x$'; but \MF\ is incapable
of dealing with such a constraint. Similarly, \MF\ can't cope with
an equation like `$x=\mathop{\rm floor}x$', which states that
$x$~is an integer. Systems of equations that involve the ↑{absolute
value} and/or ↑{floor} operation can be extremely difficult to solve,
and \MF\ doesn't pretend to be a mathematical genius.

\ddanger The rules given earlier explain how an independent variable
can become dependent or known; conversely, it's possible for a
dependent variable to become independent again, in unusual circumstances.
For example, suppose that the equation $a+b+2c=3$ in our example above
had been followed by the equation $d=b+c+a/4$. Then there would be
two dependent variables,
\begintt
## c=-0.5b-0.5a+1.5
## d=0.5b-0.25a+1.5
\endtt
Now suppose that the next statement is `|numeric|~|a|', meaning that the
old value of variable~$a$ should be discarded. \MF\ can't simply delete
an independent variable that has things depending on it, so it
chooses a dependent variable to take $a$'s place; the computer prints out
\begintt
### 0.5a=-c-0.5b+1.5
\endtt
↑↑{hash hash hash} meaning that $0.5a$ will be replaced by $-c-{1\over2}b
+{3\over2}$ in all dependencies, before $a$ is discarded. Variable $c$ is
now independent again; `↑@showdependencies@' will reveal that the only
dependent variable is now $d$, which equals $0.5c+0.75b+0.75$. \ (This
is correct, for if the variable~$a$ is eliminated from the two given
equations we obtain $4d=2c+3b+3$.) \ The variable chosen for independence
is one that has the greatest coefficient of dependency with respect
to the variable that will disappear.

\danger A designer often wants to stipulate that a certain point lies on
a certain line. ↑↑{line, point to be on} This can be done easily by
using a special feature of plain \MF\ called `↑"whatever"', which
stands for an anonymous numeric variable that has a different unknown
value each time you use it. For example,
\begindisplay
$z↓1="whatever"[z↓2,z↓3]$
\enddisplay
states that point 1 appears somewhere on the straight line that passes
through points 2 and~3. \ (The expression $t[z↓2,z↓3]$ represents that
entire straight line, as $t$ runs through all values from $-\infty$ to
$+\infty$. We want $z↓1$ to be equal to $t[z↓2,z↓3]$ for some value of~$t$,
but we don't care what value it is.) \ The expression `"whatever"$[z↓2,z↓3]$'
is legal whenever the difference $z↓2-z↓3$ is known; it's usually used
only when $z↓2$ and $z↓3$ are both known, i.e., when both points have been
determined by prior equations.

\danger Here are a few more examples of equations that involve
`"whatever"', together with their translations into English. These
equations are more fun than the ``tame'' ones we considered at the
beginning of this chapter, because they show off more of the
computer's amazing ability to deduce explicit values from implicit
statements.

\ninepoint % it's all dangerous from here on!
\setbox0=\hbox{\indent$z↓7-z↓6="whatever"\ast(z↓3-z↓2)$\quad}
\longesteq=\wd0
\noindent\hbox to\longesteq{\indent\kern-1pt\sl Equation\hfil}%
\kern-1pt{\sl Translation}\smallskip

\\$z↓5-z↓4="whatever"\ast\mathop{\rm dir}30$\\
The angle between points 4 and~5 will be $30↑\circ$ above the horizon.
\ (This equation can also be written `$z↓4=z↓5+"whatever"\ast\mathop{\rm
dir}30$', which states that point~4 is obtained by starting at point~5
and moving by some unspecified multiple of ↑{dir}$\,30$.)

\\$z↓7-z↓6="whatever"\ast(z↓3-z↓2)$\\
The line from point~6 to point~7 should be ↑{parallel} to the
line from point~2 to point~3.

\\$\penpos8("whatever",60)$\\
The simulated pen angle at point~8 should be 60 degrees; the breadth
of the pen is unspecified, so it will be determined by other equations.

\dangerexercise If $z↓1$, $z↓2$, $z↓3$, and $z↓4$ are known points,
how can you tell \MF\ to compute the point $z$ that lies on the
↑{intersection} of the lines $z↓1\to z↓2$ and $z↓3\to z↓4$?
\answer $z="whatever"[z↓1,z↓2]$; $z="whatever"[z↓3,z↓4]$. \ (Incidentally,
it's interesting to watch this computation in action. Run \MF\ with
|\tracingequations:=|\allowbreak|tracingonline:=1| and say, for example,
\begintt
z=whatever[(1,5),(8,19)]; z=whatever[(0,17),(6,1)];
\endtt
the solution appears as if by magic.
If you use |alpha| and |beta| in place of the whatevers, the machine will
also calculate values for "alpha" and "beta".)

\dangerexercise Given five points $z↓1$, $z↓2$, $z↓3$, $z↓4$, and $z↓5$,
explain how to compute $z$ on the line $z↓1\to z↓2$ such that the line
$z\to z↓3$ is parallel to the line $z↓4\to z↓5$.
\answer $z="whatever"[z↓1,z↓2]$; $z-z↓3="whatever"\ast(z↓5-z↓4)$.

\dangerexercise What \MF\ equation says that the line between points
11 and~12 is {\sl↑{perpendicular}\/} to the line between points 13 and~14?
\answer $z↓{11}-z↓{12}="whatever"\ast(z↓{13}-z↓{14})$ ↑{rotated} 90,
assuming that $z↓{13}-z↓{14}$ is known.  \ (It's also possible to say
`$(z↓{11}-z↓{12})\mathbin{\rm dotprod} (z↓{13}-z↓{14})=0$', ↑↑{dotprod}
although this risks overflow if the coordinates are large.)

\dangerexercise (For mathematicians.) \ Given three points $z↓1$, $z↓2$,
and $z↓3$, explain how to compute the distance from $z↓1$ to the straight
line through $z↓2$ and $z↓3$.
\answer One solution constructs the point $z↓4$ on $z↓2\to z↓3$ such
that $z↓4\to z↓1$ is perpendicular to $z↓2\to z↓3$, using ideas like
those in the previous two exercises: `$z↓4="whatever"[z↓2,z↓3]$;
$z↓4-z↓1="whatever"\ast(z↓3-z↓2)$ rotated 90'. Then the requested distance
↑↑{abs} ↑↑{ypart}
is $length(z↓4-z↓1)$. But there's a slicker solution: Just calculate
$$\hbox{abs ypart$((z↓1-z↓2)\mathbin{\rm rotated}-angle(z↓3-z↓2))$.}$$

\ddangerexercise (For mathematicians.) \ Given three points $z↓1$,
$z↓2$, $z↓3$, and a length~$l$, explain how to compute the two points
on the line $z↓2\to z↓3$ that are at distance~$l$ from $z↓1$. \ (Assume
that $l$~is greater than the distance from $z↓1$ to the line.)
\answer It would be nice to say simply `$z="whatever"[z↓2,z↓3]$' and
then to be able to say either `length$(z-z↓1)=l$' or `$z-z↓1=(l,0)$ rotated "whatever"';
but neither of the second equations is legal. \ (Indeed, there couldn't
possibly be a legal solution that has this general flavor, because any
such solution would determine a unique $z$, while there are two points to
be determined.) \ The best way seems to be to compute $z↓4$ as in the
previous exercise, ↑↑{pythagorean subtraction} and then to let
$v=(l\mathbin{+{-}+}\mathop{\rm length} (z↓4-z↓1))\ast\mathop{\rm
unitvector}(z↓3-z↓2)$; ↑↑{unitvector} ↑↑{length}
the desired points are then $z↓4+v$ and $z↓4-v$.

\ddangerexercise The applications of "whatever" that we have seen so far
have been in equations between {\sl pairs\/} of numeric values, not
in equations between simple numerics. Explain why an equation like
`$a+2b="whatever"$' would be useless.
\answer Such an equation tells us nothing new about $a$ or $b$. Indeed,
each use of "whatever" introduces a new independent variable, and
each new independent variable ``uses up'' one equation, since we need
$n$ equations to determine the values of $n$~unknowns. On the other hand
an equation between pairs counts as two equations; so there's a net
gain of one, when "whatever" appears in an equation between pairs.

\danger All of the equations so far in this chapter have been between numeric
expressions or pair expressions. But \MF\ actually allows equations
between any of the eight types of quantities. For example, you can write
\begintt
s1="go"; s1&s1=s2
\endtt
if $s↓1$ and $s↓2$ are string variables; this makes $s↓1=\null$|"go"|
and $s↓2=\null$|"gogo"|. Moreover, the subsequent equations
\begintt
s3=s4; s5=s6; s3=s5; s4=s1&"sh"
\endtt
will make it possible for the machine to deduce that $s↓6=\null$|"gosh"|.

\danger But nonnumeric equations are not as versatile as numeric
ones, because \MF\ does not perform operations on unknown quantities
↑↑{unknown quantities, nonnumeric}
of other types. For example, the equation
\begintt
"h"&s7="heck"
\endtt
cannot be used to define $s↓7=\null$|"eck"|, because the ↑{concatenation}
operator~|&| works only with strings that are already known.

\ddanger After the declaration `|string| |s[]|' and the equations
`|s1=s2=s3|', the statement `|show|~|s0|' will produce the result
`|unknown| |string| |s0|'; but `|show|~|s1|' will produce `|unknown|
|string| |s2|'. Similarly, `|show|~|s2|' and `|show|~|s3|' will produce
`|unknown| |string| |s3|' and `|unknown| |string| |s1|', respectively.  In
general, when several nonnumeric variables have been equated they will
point to each other in some cyclic order.

\endchapter

A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Chapter 10. Assignments

Variables usually get values by appearing in equations, as described in
the preceding chapter. But there's also another way, in which `↑|:=|'
is used instead of~`|=|'. For example, the |io.mf| program in Chapter~5
said
\begintt
stem# := trial_stem * pt#
\endtt
when it wanted to define the value of |stem#|.

The ↑{colon-equal} operator `|:=|' means ``discard the previous value of
the variable and assign a new one''; we call this an {\sl↑{assignment}\/}
operation. It was convenient for |io.mf| to define |stem#| with an
assignment instead of an equation, because |stem#| was getting several
different values within a single font. The alternative would have been to say
\begintt
numeric stem#; stem# = trial_stem * pt#
\endtt
(thereby specifically undefining the previous value of |stem#| before using
it in an equation); this is more cumbersome.

The variable at the left of `|:=|' might appear also in the expression on
the right. For example,
\begintt
code := code + 1
\endtt
means ``increase the value of "code" by 1.'' This assignment would make no
sense as an equation, since `$"code"="code"+1$' is inconsistent. The former
value of "code" is still relevant on the right-hand side when `$"code"+1$'
is evaluated in this example, because old values are not discarded until
the last minute; they are retained until just before a new assignment is made.

\dangerexercise Is it possible to achieve the effect of `$"code":="code"+1$'
by using equations and @numeric@ declarations but not assignments?
\answer Yes, but it must be done in two steps: `@numeric@ "newcode";
$"newcode"="code"+1$; @numeric@ "code"; $"code"="newcode"$'.

Assignments are permitted only when the quantity at the left of the `|:=|'
is a variable. For example, you can't say `|code+1:=code|'. More
significantly, things like `|(x,y):=(0,0)|' are not permitted, although
you can say `|w:=(0,0)|' if~$w$~has been declared to be a variable of
type @pair@. This means that a statement like `|z1:=z2|' is illegal, because
it's an abbreviation for the inadmissible construction `|(x1,y1):=(x2,y2)|';
we must remember that |z1| is not really a variable, it's a pair of variables.

The restriction in the previous paragraph is not terribly significant, because
assignments play a relatively minor r\↑ole in \MF\ programs. The best
programming strategy is usually to specify equations instead of assignments, because
equations indicate the relationships between variables in a declarative
↑↑{declarative versus imperative} ↑↑{imperative versus declarative}
manner. A person who makes too many assignments is still locked into the habits
of old-style ``imperative'' programming languages in which it is necessary
to tell the computer exactly how to do everything; \MF's equation
mechanism liberates us from that more complicated style of programming,
because it lets the computer take over the job of solving equations.

The use of assignments often imposes a definite order on the statements of
a program, because the value of a variable is different before and after
an assignment takes place. Equations are simpler because they can usually
be written down in any order that comes naturally to you.

Assignments do have their uses; otherwise \MF\ wouldn't bother with
`|:=|' at all. But experienced \MF\ programmers introduce assignments
sparingly---only when there's a good reason for doing so---because
equations are generally easier to write and more enlightening to read.

\danger \MF's ↑{internal quantities} like "tracingequations" always have
known numeric values, so there's no way to change them except by giving
assignments. The computer experiment in Chapter~9 began with
\begintt
\tracingequations:=tracingonline:=1;
\endtt
this illustrates the fact that multiple assignments are possible, just
like multiple equations. Here is the complete syntax for equations
and assignments:
\beginsyntax
<equation>\is<expression>[=]<right-hand side>
<assignment>\is<variable>[:=]<right-hand side>
<right-hand side>\is<expression>\alt<equation>\alt<assignment>
\endsyntax
Notice that the syntax permits mixtures like `$a+b=c:=d+e$'; this is
the same as the assignment `$c:=d+e$' and the equation `$a+b=c$'.

\ddanger In a mixed equation/assignment like `$a+b=b:=b+1$', the old
value of~$b$ is used to evaluate the expressions. For example, if $b$ equals~3
before that statement, the result will be the same as `$a+3=b:=3+1$';
therefore $b$ will be set to~4 and $a$~will be set to~1.

\dangerexercise Suppose that you want variable $x↓3$ to become ``like new,''
↑↑{variables, reinitializing} ↑↑{reinitializing} ↑↑{independent variables}
completely independent of any value that it formerly had; but you don't
want to destroy the values of~$x↓1$ and~$x↓2$. You can't say `↑@numeric@
$x[\,]$', because that would obliterate all the $x↓k$'s. What can you do
instead?
\answer The assignment `$x↓3:=\null$↑"whatever"' does exactly what you want.

\ddangerexercise Apply \MF\ to the short program
\begindisplay
@string@ $s[\,]$; \ $s↓1=s↓2=s↓3=s↓4$; \ $s↓5=s↓6$; \ $s↓2:=s↓5$; \
 @showvariable@ $s$;
\enddisplay
and explain the results you get.
\answer The result shows that $s↓1=s↓3=s↓4$ and $s↓2=s↓5=s↓6$ now:
\begintt
s[]=unknown string
s1=unknown string s3
s2=unknown string s6
s3=unknown string s4
s4=unknown string s1
s5=unknown string s2
s6=unknown string s5
\endtt
(The assignment $s↓2:=s↓5$ broke $s↓2$'s former relationship with $s↓1$,
$s↓3$, and $s↓4$.)

\ddanger If other variables depend on $v$ when $v$ is assigned a new value,
the other variables do not change to reflect the new assignment; they still
act as if they depended on the previous (unknown) value of~$v$. For example,
if the equations `$2u=3v=w$' are followed by the assignment `$w:=6$', the
values of $u$ and~$v$ won't become known, but \MF\ will still remember the
fact that $v=.66667u$. \ (This is not a new rule; it's a consequence of
the rules already stated. When an independent variable is discarded, a
dependent variable may become independent in its place, as described in
Chapter~9.)

\ddangerexercise Apply \MF\ to the program
\begindisplay
$"tracingequations":="tracingonline":=1$;\cr
$a=1$; \ $a:=a+b$; \ $a:=a+b$; \ $a:=a+b$;\cr
@show@ $a,b$;\cr
\enddisplay
and explain the results you get.
\answer The results are
\begindisplay
|## a=1|\cr
|## a=b+1|&(after the first assignment)\cr
|## b=0.5a-0.5|&(after the second assignment)\cr
|### -1.5a=-%CAPSULEnnnn-0.5|&(after the third assignment)\cr
|>> a|&(after `@show@'; variable $a$ is independent)\cr
|>> 0.33333a-0.33333|&(this is the final value of $b$)\cr
\enddisplay
↑↑|CAPSULE| Let $a↓k$ denote the value of $a$ after $k$ assignments were made.
Thus, $a↓0=1$, and $a↓1$ was dependent on the independent variable~$b$.
Then $a↓1$ was discarded and $b$ became dependent on the independent
variable~$a↓2$. The right-hand side of the third assignment was
therefore $a↓2+b$. At the time $a↓2$ was about to be discarded, \MF\
had two dependencies $b=0.5a↓2-0.5$ and $\kappa=1.5a↓2-0.5$, where
$\kappa$ was a nameless ``↑{capsule}'' inside of the computer, representing
the new value to be assigned. Since $\kappa$ had a higher coefficient
of dependency than~$b$, \MF\ chose to make $\kappa$ an independent variable,
after which $-1.5a↓2$ was replaced by $-\kappa-0.5$ in all dependencies; hence
$b$ was equal to $0.33333\kappa-0.33333$. After the third
assignment was finished, $\kappa$ disappeared and $a↓3$ became independent
in its place. \ (There's a 50-50 chance that the line `|##| |a=%CAPSULEnnnn|'
was also printed after the third assignment; this means that $a$ was
temporarily dependent on $\kappa$, before $\kappa$ was discarded. If
the equation $a=\kappa$ happened to make $\kappa$ dependent on~$a$, rather
than vice versa, no ↑↑{hash hash} `|##|' line was printed; such lines are
omitted when a capsule or part of a capsule has been made dependent, unless
you have made ↑"tracingcapsules"$\null>0$.)

\endchapter

A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Chapter 11. Magnification

A single \MF\ program can produce fonts of type for many different kinds
of printing equipment, if the programmer has set things up so that the
↑{resolution} can be varied. The ``plain \MF\thinspace'' base file described
in Appendix~B establishes a set of conventions that make such variability
quite simple; the purpose of the present chapter is to explain those
conventions.

For concreteness let's assume that our computer has two output devices.
One of them, called ↑"cheapo", has a resolution of 200 pixels per
inch (approximately 8 per millimeter); the other, called ↑"luxo",
has a resolution of 2000 pixels per inch. We would like to write \MF\
programs that are able to produce fonts for both devices. For example,
if the file |newface.mf| contains a program for a new typeface, we'd
like to generate a low-resolution font by invoking \MF\ with
\begintt
\mode=cheapo; input newface;
\endtt
the same file should also produce a high-resolution font if we start with
\begintt
\mode=luxo; input newface
\endtt
instead. Other people with different printing equipment should also be
able to use |newface.mf| with their own favorite ↑"mode" values.

The way to do this with plain \MF\ is to call ↑@mode\_setup@ near the
beginning of |newface.mf|; this routine establishes the values of
variables like ↑"pt" and ↑"mm", which represent the respective numbers of
pixels in a point and a millimeter. For example, when $"mode"= "cheapo"$,
the values will be $"pt"=2.7674$ and $"mm"=7.87402$; when $"mode"="luxo"$,
they will be $"pt"=27.674$ and $"mm"=78.74017$.  The |newface.mf| program
should be written in terms of such variables, so that the pixel patterns
for characters will be about 10~times narrower and 10~times shorter in
"cheapo" mode than they are in "luxo" mode. For example, a line that's
drawn from $(0,0)$ to $(3"mm",0)$ will produce a line that's about 23.6
pixels long in "cheapo" mode, and about 236.2 pixels long in "luxo" mode;
the former line will appear to be 3\thinspace mm long when printed by
"cheapo", while the latter will look 3\thinspace mm long when printed by
"luxo".

A further complication occurs when a typeface is being ↑{magnified}, so that
the font does not correspond to its normal size. For example, we might
want to have a set of fonts for "cheapo" that are twice as big as usual,
so that users can make transparencies for overhead projectors. \ (Such
output could also be reduced to 50\% of its size as printed,
on suitable reproduction equipment, thereby increasing the effective
resolution from 200 to 400.) \ \TeX\ allows entire jobs to be magnified
by a factor of~2 if the user says `|\magnification=2000|'; individual
fonts can also be magnified in a \TeX\ job by saying, e.g., ↑↑{TeX}
`|\font\f=newface| |scaled| |2000|'. The standard way to produce a font
with two-fold magnification using the conventions of plain \MF\ is to say, e.g.,
\begintt
\mode=cheapo; mag=2; input newface;
\endtt
this will make $"pt"=5.5348$ and $"mm"=15.74803$.

The @mode\_setup@ routine looks to see if ↑"mag" has a known value;
if not, it sets $"mag"=1$. Similarly, if "mode" is unknown,
↑↑"proof" @mode\_setup@ sets $"mode"="proof"$.

Plain \MF\ also computes the values of several other dimension-oriented
values in addition to "pt" and "mm", corresponding to the dimensions
that are understood by \TeX. Here is the complete list:
\begindisplay \openup 1pt
"pt"&printer's point&($\rm72.27\,pt=1\,in$)\cr
↑"pc"&pica&($\rm1\,pc=12\,pt$)\cr
↑"in"&inch&($\rm1\,in=2.54\,cm$)\cr
↑"bp"&big point&($\rm72\,bp=1\,in$)\cr
↑"cm"¢imeter&($\rm100\,cm=1\,meter$)\cr
"mm"&millimeter&($\rm10\,mm=1\,cm$)\cr
↑"dd"&did\↑ot point&($\rm1157\,dd=1238\,pt$)\cr
↑"cc"&cicero&($\rm1\,cc=12\,dd$)\cr
\enddisplay
In each case the values are rounded to the nearest $1\over65536$th of a pixel.

Although such standard physical ↑{dimensions} are available, they haven't
been used very much in traditional typefaces; designers usually specify
other units like `"em"' or `"x\_height"' in order to define the sizes
of letters, and such quantities generally have ad hoc values that vary
from font to font.  Plain \MF\ makes it easy to introduce ↑{ad hoc
dimensions} that will vary with the resolution and the magnification just
as "pt" and "mm" do; all you have to do is define ``↑{sharped}''
dimensions that have the same name as your pixel-oriented dimensions, but
with `|#|' ↑↑{hash} tacked on as a suffix. For example, $"em"\0$ and
$"x\_height"\0$ (typed `|em#|' and `|x_height#|'\thinspace) would be the
↑{sharped dimensions} corresponding to "em" and "x\_height". Plain \MF\ has
already defined the quantities $"pt"\0$, $"pc"\0$, $"in"\0$, $"bp"\0$,
$"cm"\0$, $"mm"\0$, $"dd"\0$, and $"cc"\0$ for the standard units named above.

Sharped dimensions like $"em"\0$ and $"x\_height"\0$ should always be
defined in terms of resolution-independent dimensions like $"pt"\0$,
$"in"\0$, etc., so that their values do not change in any way when "mode"
and "mag" are varied. The `|#|' sign implies unchangeability.
After @mode\_setup@ has been called,
the pixel-oriented dimensions can be calculated by simply saying
\begindisplay
↑@define\_pixels@("em", "x\_height").
\enddisplay
This statement is an abbreviation for
\begindisplay
$"em":="em"\0\ast"hppp"$;&$"x\_height":="x\_height"\0\ast"hppp"$
\enddisplay
where ↑"hppp" is an internal variable of \MF\ that represents the number
of pixels per point in the horizontal dimension. Any number of ad hoc
dimensions can be listed in a single @define\_pixels@ statement.

Chapter 5's demonstration program |io.mf| contains several examples of ad hoc
dimensions defined in this way, and it also contains the statement
\begindisplay
↑@define\_blacker\_pixels@("thin", "thick");
\enddisplay
what's this? Well, Appendix B makes that statement an abbreviation for
\begindisplay
$"thin":="thin"\0\ast"hppp"+"blacker"$;&
$"thick":="thick"\0\ast"hppp"+"blacker"$;\cr
\enddisplay
in other words, the sharped dimensions are being unsharped in this case
by converting them to pixels and then adding `"blacker"'. The variable
↑"blacker" is a special correction intended to help adapt a font to the
idiosyncrasies of the current output device; @mode\_setup@ uses the value
of "mode" to establish the value of "blacker". For example, "cheapo" mode
might want $"blacker"=0.65$, while "luxo" mode might give best results
when $"blacker"=0.1$. The general convention is to add "blacker" to
pixel-oriented variables that determine the breadth of pens and the
thickness of stems, so that the letters will be slightly darker on machines
that otherwise would make them appear too light. Different machines treat
pixels quite differently, because they are often based on quite different
physical principles. For example, the author once worked with an extremely
high-resolution device that tended to shrink stem lines rather drastically
when it used a particular type of photographic paper, and it was necessary
to set $"blacker"=4$ to get proper results on that machine; another
high-resolution device seems to want "blacker" to be only~$0.2$. Experimentation
is necessary to tune \MF's output to particular devices, but the author's
experience suggests strongly that such a correction is worthwhile. When
↑↑"proof" $"mode"="proof"$ or ↑"smoke", the value of "blacker" is taken to
be zero, since the output in these modes is presumably undistorted.

\exercise Does `$"mode"="cheapo"$; $"mag"=10$' produce exactly the same
font as `$"mode"="luxo"$', under the assumptions of this chapter?
\answer Almost, but not quite. The values of standard dimension variables
like "pt" and "mm" will be identical in both setups, as will the values of
ad~hoc dimension variables like "em" and "x\_height". But pen-oriented
dimensions that are defined via @define\_blacker\_pixels@ will be slightly
different, because "cheapo" mode has $"blacker"=0.65$ while "luxo" mode
has $"blacker"=0.1$ (since the "luxo" printer has different physical
characteristics).  Similarly, @define\_corrected\_pixels@ (which we are
just about to discuss) will produce slightly different results in the two
given modes.

\danger Line 7 of |io.mf| says `↑@define\_corrected\_pixels@($o$)', and
this is yet a third way of converting from true physical dimensions to
pixel-oriented values. According to Appendix~B, variable~$o$ is defined by
the assignment
\begindisplay
$o:=\round(o\0\ast"hppp"\ast"o\_correction")+"epsilon"$
\enddisplay
↑↑{round} ↑↑"epsilon" ↑↑"o"
where ↑"o\_correction", like "blacker", is a magic number that depends on
the output device for which fonts are being made. On a high-resolution
device like "luxo", the appropriate value for the "o\_correction" factor
is~1, but on a low-resolution device like "cheapo" the author has obtained
more satisfactory results with $"o\_correction"=0.4$. The reason is that
`$o$' is used to specify the number of pixels by which certain features
of characters ``↑{overshoot}'' the baseline or some other line to which
they are visually related. High-resolution curves look better when they
overshoot in this way, but low-resolution curves do not; therefore it is
usually wise to curtail the amount of overshoot by applying the
"o\_correction" factor. In "proof" and "smoke" modes the factor is
equal to 1.0, since these modes correspond to high resolution.

%\danger Plain \MF\ also provides a fourth way to define unsharped
%dimensions from sharped ones, if you want the unsharped dimensions
%to be rounded to the nearest integer number of pixels: Just say
%`↑@define\_whole\_pixels@'. For example,
%\begindisplay
%@define\_whole\_pixels@("foo")
%\enddisplay
%stands for `$"foo":=\round("foo"\0\ast"hppp")$'.

\ddanger The sharped forms of dimensions are actually represented by plain
\MF\ in terms of printer's points, so that `$"pt"\0$' turns out to be
equal to~1.  However, it is best for programmers not to make use of this
fact; a program ought to say, e.g., `$"em"\0:=10"pt"\0$', even though
the `$"pt"\0$' in this construction is redundant, and even though the
computer would run a few microseconds faster without it.

\ddanger Each output device for which you will be generating fonts should
be represented by a symbolic ↑"mode" name in the implementation of \MF\
that you are using. Since these mode names vary from place to place, they
are not standard aspects of the \MF\ language; for example, it is doubtful
whether the hypothetical "cheapo" and "luxo" modes discussed in this
chapter actually exist anywhere. The plain \MF\ base is intended to be
extended to additional modes in a disciplined way, as described in
Appendix~B.

\ddanger It's easy to create a new symbolic mode. First you assign it a
previously unused number (e.g., `$"luxo":=28$'\thinspace), and then
you define a bunch of table entries, such as
\begindisplay
$"pixels\_per\_inch\_"["luxo"]:=2000$;&|%| high res, almost 30 per point\cr
$"blacker\_"["luxo"]:=.1$;&|%| make pens a teeny bit blacker\cr
$"o\_correction\_"["luxo"]:=1$;&|%| and keep the full overshoot\cr
$"proofing\_"["luxo"]:=0$;&|%| no, we're not making proofs\cr
$"fontmaking\_"["luxo"]:=1$;&|%| yes, we are making a font\cr
$"tracingtitles\_"["luxo"]:=1$;&|%| yes, show titles online\cr
\enddisplay
(Notice the final underline in names like `"blacker\_"' here.) \
These assignments should appear in an auxiliary file that is loaded together
with |plain.mf| when the plain base is created at your installation.
The last three of these table entries specify values that @mode\_setup@ will
assign to \MF's internal variables ↑"proofing", ↑"fontmaking", and
↑"tracingtitles"; they affect the amount of output that will be produced,
as explained later. In general, "proofing" and "fontmaking" are usually
set to 0 and~1, respectively, in modes that are intended for font
production rather than initial font design; "tracingtitles" is usually
0~for low-resolution fonts (which are generated quickly), but 1~for
high-resolution fonts (which go more slowly), because detailed online
progress reports are desirable when comparatively long jobs are running.

\ddanger Besides the six mandatory table entries `"pixels\_per\_inch\_"',
\dots, `"tracingtitles\_"' just discussed, each mode can also have a
table entry called `↑"aspect\_ratio\_"'.
If "aspect\_ratio\_"["luxo"] is unspecified, it means that "luxo" mode
generates fonts that are assumed to have square pixels; but if, for
example, $"aspect\_ratio\_"["luxo"]:=5/4$, it means that the pixels output
by "luxo" are assumed to be ↑{nonsquare} in the ratio of 5 to~4; i.e.,
5~vertical pixel units are equal to 4~horizontal pixel units. The
pixel-oriented dimensions of plain \MF\ are given in terms of horizontal
pixel units, so an aspect ratio of 5/4 together with 2000 pixels per inch
would mean that there are 2500 vertical pixel units per inch; a square
inch would consist of 2500 rows of pixels, with 2000 pixels in each row. \
(Stating this another way, each pixel would be $1\over2000$ inches wide and
$1\over2500$ inches high.) \ In such a case plain \MF\ will set the
↑"currenttransform" variable so that all @draw@ and @fill@ commands
stretch the curves by a factor of 5/4 in the vertical dimension; this
compensates for the nonsquare pixels, so the typeface designer doesn't have to
be aware of the fact that pixels aren't square.

\ddanger Each mode can also have an `↑"extra\_"' parameter, which sets up
any special things that the mode might want to do in a nonstandard way;
the value of this parameter should be a string that contains one or more
\MF\ commands.  For example, $"extra\_"["smoke"]$ is |"grayfont|
|black;let| |makebox=maketicks"|; this changes the style of proofsheets
that you get in ↑"smoke" mode.

Let's look now at a concrete example, so that it will be clear how the
ideas of device-independent font design can be implemented in practice.
We shall study a file |logo.mf| that generates the seven letters of
\MF's ↑{logo}. There also are ``↑{driver}'' files |logo10.mf|, |logo9.mf|,
etc., which use |logo.mf| to produce fonts in various sizes. For
example, a font containing the 10-point characters `\thinspace\MF\thinspace'
could be generated for the hypothetical "luxo" printer by running \MF\ with
\begintt
\mode=luxo; input logo10
\endtt
if "luxo" mode really existed.

The main purpose of |logo10.mf| is to establish the ``sharped'' values of
several ad hoc dimensions; then it inputs |logo.mf|, which does the
rest of the work. Here is the entire file |logo10.mf|:
\begintt
% 10-point METAFONT logo|smallskip
font_size 10pt#;   % the "design size" of this font
ht#:=6pt#;         % height of characters
xgap#:=0.6pt#;     % horizontal adjustment
u#:=4/9pt#;        % unit width
s#:=0;             % extra space at the left and the right
o#:=1/9pt#;        % overshoot
px#:=2/3pt#;       % horizontal thickness of pen
input logo         % now generate the font
end                % and stop
\endtt
Similar files |logo9.mf| and |logo8.mf| will produce 9-point
`\thinspace{\manual hijklmnj}\thinspace' and 8-point
`\thinspace{\manual opqrstuq}\thinspace'; the letters get a little
wider in relation to their height, and the inter-character spacing
gets significantly wider, as the size gets smaller:
\begintt
% 9-point METAFONT logo        % 8-point METAFONT logo|smallskip
font_size 9pt#;                font_size 8pt#;
ht#:=.9*6pt#;                  ht#:=.8*6pt#;
xgap#:=.9*0.6pt#;              xgap#:=.8*0.6pt#;
u#:=.91*4/9pt#;                u#:=.82*4/9pt#;
s#:=.08pt#;                    s#:=.2pt#;
o#:=1/10pt#;                   o#:=1/12pt#;
px#:=.9*2/3pt#;                px#:=.8*2/3pt#;
input logo                     input logo
end                            end
\endtt
It is interesting to compare the font generated by |logo10.mf| to the
font generated by |logo8.mf| with |mag=10/8|: Both fonts will have
the same values of "ht", "xgap", and "px", when the magnification has been
taken into account. But the magnified 8-point font has a slightly larger
value of "u" and a positive value of "s"; this changes
`\thinspace\MF\thinspace' to `\thinspace{\manual/0123451}\thinspace'.

\danger Every font has a ``↑{design size},'' which is a more-or-less
arbitrary number that reflects the size of type it is intended to blend
with.  ↑↑{TeX} Users of \TeX\ select magnified fonts in two ways, either
by specifying an ``at size'' or by specifying a scale factor (times 1000).
For example, the 8-point \MF\ logo can be used at 10/8 magnification by
referring either to `|logo8| |at|~|10pt|' or to `|logo8| |scaled|~|1250|'
in a \TeX\ document.  When an ``↑{at size}'' is specified, the amount of
magnification is the stated size divided by the design~size. A typeface
designer can specify the design size by using plain \MF's `↑@font\_size@'
command as illustrated on the previous page. \ (If no design size is
specified, \MF\ will set it to $128\pt$, by default.)

The file |logo.mf| itself begins by defining three more ad hoc dimensions
in terms of the parameters that were set by the driver file; these
dimensions will be used in several of the programs for individual letters.
Then |logo.mf| makes the conversion to pixel units:
\begintt
% Routines for the METAFONT logo
% (logo10.mf is a typical driver file)
mode_setup;
ygap#:=xgap#;                     % vertical adjustment
leftstemloc#:=2.5u#+s#;           % position of left stems
barheight#:=.45ht#;               % height of bar lines
define_pixels(s,u,xgap,ygap,leftstemloc,barheight);
py#:=.9px#; define_blacker_pixels(px,py); % pen dimensions
pickup pencircle xscaled px yscaled py; logo_pen:=savepen;
define_corrected_pixels(o);
\endtt
There's nothing new here except the use of `↑"savepen"' in the
second-last line; this, as we will see in Chapter~16, makes the
currently-picked-up pen available for repeated use in the
subsequent program.

After the initial definitions just shown, |logo.mf| continues with
programs for each of the seven letters. For example,
here is the program for `{\manual ↑{E}}', which illustrates the
\rightfig 11a ({224\apspix} x {216\apspix}) ↑-11pt
use of $u\0$, $s\0$, $"ht"\0$, "leftstemloc", "barheight", "xgap",
and "logo\_pen":
\begintt
beginchar("E",14u#+2s#,ht#,0);
pickup logo_pen;
x1=x2=x3=leftstemloc;
x4=x6=w-x1+o; x5=x4-xgap;
y1=y6; y2=y5; y3=y4;
bot y1=0; top y3=h;
y2=barheight;
draw z6--z1--z3--z4; draw z2--z5;
labels(1,2,3,4,5,6);
endchar;
\endtt
We have seen the essentials of the {\manual M} and the {\manual T} in
Chapter~4; programs for the other letters will appear later.

\exercise The ad hoc dimensions $"ht"\0$, $"xgap"\0$, $u\0$, $s\0$,
$o\0$, and $"px"\0$ defined in the driver files all affect the letter
`{\manual E}' defined by this program. For each of these dimensions,
tell what would happen to the `{\manual E}' if that dimension were
increased slightly while all the others stayed the same.
\answer Increasing $"ht"\0$ would make the letter shape and the bounding
box taller; increasing $"xgap"\0$ would move point~5 to the left, thereby
making the middle bar shorter; increasing $u\0$ would make the shape and
its bounding box wider; increasing $s\0$ would widen the bounding box
at both sides without changing the letter shape; increasing $o\0$ would
move points 4,~5, and~6 to the right; increasing $"px"\0$ would make
the pen thicker (preserving the top edge of the upper bar, the bottom
edge of the lower bar, and the center of the middle bar and the stem).

\dangerexercise Guess the program for `{\manual l}' (which is ↑↑{F}
almost the same as `{\manual i}'\thinspace).
\answer The only possible surprise is the position of $y↓1$,
which should match similar details in the `{\manual h}'
and the~`\kern1pt{\manual j}\kern1pt' of Chapter~4:
\begintt
beginchar("F",14*u#+2s#,ht#,0); pickup logo_pen;
x1=x2=x3=leftstemloc; x4=w-x1+o; x5=x4-xgap;
y2=y5; y3=y4; bot y1=-o; top y3=h; y2=barheight;
draw z1--z3--z4; draw z2--z5;
labels(1,2,3,4,5); endchar;
\endtt

\dangerexercise Write the complete programs for `{\manual h}' ↑↑{M} ↑↑{T}
and `\kern1pt{\manual j}\kern1pt', based on the information in Chapter~4,
but using the style of the program for `{\manual E}' above.  The character
widths should be $18u\0+2s\0$ and $13u\0+2s\0$, respectively.
\answer The quantity called "ss" in Chapter~4 is now "leftstemloc".
\begintt
beginchar("M",18*u#+2s#,ht#,0); pickup logo_pen;
x1=x2=leftstemloc; x4=x5=w-x1; x3=w-x3;
y1=y5; y2=y4; bot y1=-o; top y2=h+o; bot y3=ygap;
draw z1--z2--z3--z4--z5;
labels(1,2,3,4,5); endchar;|smallskip
beginchar("T",13*u#+2s#,ht#,0); pickup logo_pen;
lft x1=0; x2=w-x1; x3=x4=.5w;
y1=y2=y3; top y1=h; bot y4=-o;
draw z1--z2; draw z3--z4;
labels(1,2,3,4); endchar;
\endtt

\danger The file |logo.mf| also contains the following cryptic instructions,
which cause the letter pairs `\kern1pt{\manual jk}' and `{\manual lm}' to
be typeset closer together than their bounding boxes would imply:
\begintt
ligtable "T": "A" kern -.5u#;
ligtable "F": "O" kern -u#;|smallskip
\endtt
Without these corrections `\MF\kern1pt' would be ↑↑{kerning} ↑↑@kern@
`{\manual hij\/kl\/mnj}\kern1pt'.  Uppercase letters are often subject to
such spacing corrections, especially in logos; \TeX\ will adjust the spacing
if the typeface designer has supplied ↑@ligtable@ information like this.

\danger Finally, |logo.mf| closes with four more commands, which provide
further information about how to typeset with this font:
\begintt
font_quad  18u#+2s#;
font_normal_space  6u#+2s#;
font_normal_stretch  3u#;
font_normal_shrink  2u#;
\endtt
A ↑@font\_quad@ is the unit of measure that a \TeX\ user calls one `|em|'
when this font is selected. The normal space, stretch, and shrink parameters
↑↑@font\_normal\_space@ ↑↑@font\_normal\_stretch@ ↑↑@font\_normal\_shrink@
define the interword spacing when text is being typeset in this font.
Actually a font like |logo10| is rarely used to typeset anything except
the one word, `\MF\kern1pt'; but the spacing parameters have been
included just in case somebody wants to typeset a sentence like
`{\manual kn illiji jmhkjm ml hmnjknk mljin kji nmnlkj jmllii}'.)

\danger An optional `↑|=|' or `↑|:=|' sign may be typed after `@font\_size@',
`@font\_quad@', etc., in case you think the file looks better that way.

\danger Notice that ``sharped'' units must be given in the ↑@ligtable@
kerning commands and in the definition of device-independent
parameters like @font\_size@
and @font\_quad@. Appendix~F discusses the complete rules of @ligtable@
and other commands by which \MF\ programs can send important information
to typesetting systems like \TeX. Adding these extra bits of information
to a \MF\ program after a font has been designed is something like
adding an index to a book after that book has been written and proofread.

\ddangerexercise What's the longest English word that can be typeset
with the font |logo9|?
\answer `{\manual nmnkjmnihinj}'; possibly also `{\manual hijklmmjnmji}'.

\ninepoint	% nothing but danger from here on, folks
\danger Let's summarize the general contents of |logo.mf|, now that we
have seen it all, because it provides an example of a complete typeface
description (even though there are only seven letters):\enddanger

\smallskip
\item\bull The file begins by defining ad hoc dimensions and converting
them to pixel units, using @mode\_setup@, @define\_pixels@, etc.

\smallskip
\item\bull Then come programs for individual letters. \ (These programs
are often preceded by macro definitions for subroutines that occur several
times. For example, we will see later that the `{\manual k}' and the
`{\manual m}' of the logo are drawn with the help of a subroutine that makes
half of a super-ellipse; the definition of this macro actually comes near
the beginning of |logo.mf|, just before the programs for the letters.)

\smallskip
\item\bull Finally there are special commands like ↑@ligtable@ and
↑@font\_quad@, to define parameters of the font that are helpful
when typesetting.

\smallskip
\item\bull The file is accompanied by driver files that define
ad hoc parameters for different incarnations of the typeface.

\smallskip\noindent
We could make lots of different driver files, which would produce
lots of different (but related) variations on the \MF\ logo; thus, |logo.mf|
defines a ``↑{meta-font}'' in the sense of Chapter~1.

\dangerexercise What changes would be necessary to generalize the |logo|
routines so that the bar-line height is not always 45 per~cent of the
character height?
\answer Delete the line of |logo.mf| that defines |barheight#|, and
insert that line into each of the driver files |logo10.mf|, |logo9.mf|,
|logo8.mf|. Then other bar-line heights are possible by providing new
driver files; another degree of ``meta-ness'' has therefore been added
to the meta-font.

\danger ↑{Assignments} (\thinspace`|:=|'\thinspace) have been used instead
of equations (\thinspace`|=|'\thinspace) in the driver files |logo10.mf|,
|logo9.mf|, and |logo8.mf|, as well as
in the opening lines of |io.mf| in Chapter~5; this contradicts the
advice in Chapter~10, where we are told to stick to equations unless
assignments are absolutely necessary. The author has found it convenient
to develop the habit of using assignments whenever ad hoc dimensions
are being defined, because he often makes experimental files in which
the ad hoc dimensions are changed several times. For example, it's a good
idea to test a particular letter with respect to a variety of different
parameter settings when that letter is first being designed; such
experiments can be done easily by copying the ad hoc parameter definitions
from driver files into a test file, provided that the parameters
have been defined with assignments instead of equations.

\danger \TeX\ users have found it convenient to have fonts in a series
of magnifications that form a geometric series. A font is said
to be scaled by `↑{magstep}~1' if it has been magnified by~1.2;
it is scaled by `magstep~2' if it has been magnified by $1.2\times1.2=1.44$;
it is scaled by `magstep~3' if it has been magnified by $1.2\times1.2\times1.2=
1.728$; and so on. Thus if a job uses a font that is scaled by magstep~2,
and if that entire job is magnified by magstep~1, the font actually used
for printing will be scaled by magstep~3. The additive nature of magsteps
makes it more likely that fonts will exist at the desired sizes when
jobs are magnified. Plain \MF\ supports this convention by allowing
constructions like
\begintt
\mode=cheapo; mag=magstep 2; input logo9
\endtt
if you want to generate the 9-point \MF\ logo for the "cheapo" printer,
magnified by 1.44 (i.e., by magstep~2). You can also write `|magstep|~|0.5|'
↑↑{TeX} for what \TeX\ calls `|\magstephalf|'; this magnifies by $\sqrt{1.2}$.

\endchapter

A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Chapter 12. Boxes

\looseness=-1
Let's pause now to take a closer look at the ``bounding boxes'' that enclose
individual characters. In olden days, metal type was cast on a
rectangular body in which each piece of type had the same vertical
extent, although the type widths would vary from character to character.
Nowadays we are free of the mechanical constraints imposed by metal type,
but the former metaphors are still useful: A~typesetting system like ↑↑{TeX}
\TeX\ imagines that each character fits into a rectangular box, and words are
typeset by putting such boxes snugly next to each other.

% Here are some macros borrowed from The TeXbook
\def\dolist{\afterassignment\dodolist\let\next= }%
\def\dodolist{\ifx\next\endlist \let\next\relax
  \else \\\let\next\dolist \fi
  \next}
\def\endlist{\endlist}
\def\\{\expandafter\if\space\next\ \else \setbox0=\hbox{\next}\maketypebox\fi}
\def\demobox#1{\setbox0=\hbox{\dolist#1\endlist}%
  \copy0\kern-\wd0\makelightbox}
 The main difference
between the old conventions and the new~ones is that type boxes are now
allowed to vary in height as well as in width. For example, when \TeX\
typesets `A~line~of~type.' it puts boxes together that essentially look
like this: `\thinspace\demobox{A line of type.}\thinspace'. \ (The `A'
appears in a box `\thinspace\setbox0\hbox{A}\maketypebox\thinspace' that
sits on a given baseline, while the `y' appears in a box
`\thinspace\setbox0\hbox{y}\maketypebox\thinspace' that descends below the
baseline.) \ \TeX\ never looks inside a box to see what character actually
appears there; \TeX's job is to put boxes together in the right places
on a page, based only on the box sizes. It is a typeface designer's job
to decide how big the boxes should be and to create the characters inside
the boxes.

Boxes are two-dimensional objects, but we ascribe three dimensions to them
because the vertical component is divided into two quantities, the
{\sl↑{height}\/} (above the ↑{baseline}) and the {\sl↑{depth}\/}
(below the baseline). The horizontal dimension is, of course, called
the {\sl↑{width}}. Here is a picture of a typical box, showing its
so-called ↑{reference point} and baseline:

{\eightpoint
\setbox0=\hbox{$\uparrow$}
\setbox1=\hbox to \wd0{$\hss\mid\hss$} % with luck, they'll line up
\setbox2=\vbox{\copy0
  \nointerlineskip \kern-.5pt \copy1
  \nointerlineskip \kern-.5pt \copy1
  \moveleft 1em\hbox{height}
  \copy1 \nointerlineskip \kern-.5pt
  \copy1 \nointerlineskip \kern-.5pt
  \hbox{$\downarrow$}
  \kern.2pt}
\setbox3=\vbox{\kern.2pt\copy0
  \moveleft 1em\hbox{depth}
  \hbox{$\downarrow$}
  \kern0pt}
\setbox4=\vtop{\kern-3pt % this cancels the null text above the samplebox
  \hbox{\samplebox{\ht2}{\ht3}{6em}{}%
    \kern-6em
    \raise3pt\hbox to 6em{\hss Baseline\hss}}
  \kern3pt
  \arrows{6em}{width}}
\medskip\indent
\setbox0=\hbox{$\vcenter{}$}% \ht0 is the axis height
\lower\ht0\hbox{Reference point$-$\kern-.2em$\rightarrow$\kern2pt}%
\raise\ht2\box4
\kern1.5em
\raise\ht2\vtop{\kern0pt\box2\nointerlineskip\box3}}

\medskip\noindent
The example characters in previous chapters have all had zero depth, but
we will soon be seeing examples in which both height and depth are relevant.

A character shape need not fit inside the boundaries of its box. Indeed,
{\it italic\/} and {\sl slanted\/} letters are put into ordinary boxes
just as if they were not slanted, so they frequently stick out at the right.
For example, the letter `g\/' in the font you are now reading (↑|cmr10|)
can be compared with the `{\sl g\/}' in the corresponding slanted
font (↑|cmsl10|):
\begindisplay
\vbox to 40pt{\ifproofmode\hrule\vfill
  \hsize=2.5in \baselineskip 6pt \fiverm\noindent
  (A figure will be inserted here; too bad you can't see it now.
  It shows two g's, as claimed. In fact, the same figure appeared
  on page 63 of The TeXbook.)
  \vfill\hrule\fi}
\enddisplay
The slanted `{\sl g\/}' has been drawn as if its box were skewed right at the
top and left at the bottom, keeping the baseline fixed; but \TeX\ is told
in both cases that the box is $5\pt$ wide, $4.3055\pt$ high, and $1.9444\pt$
deep. Slanted letters will be spaced properly in spite of the fact that their
boxes have been straightened up, because the letters will match correctly
at the baseline.

\danger Boxes also have a fourth dimension called the {\sl↑{italic
correction}}, which gives \TeX\ additional information about whether or
not a letter protrudes at the right. For example, the italic correction
for an unslanted `g\/' in |cmr10| is $0.1389\pt$, while the corresponding
slanted letter in |cmsl10| has an italic correction of $0.8565\pt$. The
italic correction is added to a box's width when math formulas like ${\rm
g}↑2$ or ${\sl g}↑2$ are being typeset, and also in other cases as
explained in {\sl The \TeX book}.

Plain \MF's ↑@beginchar@ command establishes the width, height, and depth
of a box. These dimensions should be given in terms of ``↑{sharped}''
quantities that do not vary with the resolution or magnification, because
the size of a character's type box should not depend in any way on the device
that will be used to output that character. It is important to be able to
define documents that will not change even though the technology for printing
those documents is continually evolving. \MF\ can be used to produce fonts for
new devices by introducing new ``modes,'' as we have seen in Chapter~11,
but the new fonts should still give the same box dimensions to each character.
Then the device-independent files output by \TeX\ will not have to be
changed in any way when they are printed or displayed with the help of
new equipment.

The three dimensions in a @beginchar@ command are given in reverse
alphabetical order: First comes the width, then the height, then the depth.
The @beginchar@ routine converts these quantities into pixel units
and assigns them to the three variables ↑"w", ↑"h", and~↑"d". In fact,
@beginchar@ rounds these dimensions to the nearest whole number of
pixels; hence $w$, $h$, and~$d$ will always be integers.

\MF's pixels are like squares on graph paper, with pixel boundaries
at points with integer coordinates. The left edge of the type box lies
on the line $x=0$, and the right edge lies on the line $x=w$; we have
$y=h$ on the top edge and $y=-d$ on the bottom edge. There are $w$ pixels
in each row and $h+d$ in each column, so there are exactly $wh+wd$ pixels
inside the type box.

Since $w$, $h$, and $d$ are integers, they probably do not exactly match
the box dimensions that are assumed by device-independent typesetting
systems like \TeX. Some characters will be a fraction of a pixel too wide;
others will be a fraction of a pixel too narrow. However, it's still possible
to obtain satisfactory results if the pixel boxes are stacked together
based on their $w$ values and if the accumulated error is removed in the
spaces between words, provided that the box positions do not ↑{drift}
too far away from their true device-independent locations. A designer should
strive to obtain letterforms that work well together when they are placed
together in boxes that are an integer number of pixels wide.

\ddanger You might not like the value of $w$ that @beginchar@ computes by
rounding the device-independent width to the nearest pixel boundary.
For example, you might want to make the letter~`m' one pixel wider, at
certain resolutions, so that its three stems are equally spaced or so that
it will go better with your `n'. In such a case you can assign a new value
to~$w$, at any time between @beginchar@ and ↑@endchar@. This new value
will not affect the device-independent box width assumed by \TeX, but it
should be respected by the software that typesets ↑|DVI| files using your font.

\def\hidecoords(#1,#2){\hbox to 0pt{\hss$\scriptstyle(#1,#2)$\hss}}
\setbox0=\vtop{\kern -96pt
  \rightline{\vbox{\hbox to 140\apspix{\hidecoords(0,h)\hfil\hidecoords(w,h)}
      \kern3pt
      \figbox{12a}{140\apspix}{360\apspix}\vbox
      \kern-3pt
      \hbox to 140\apspix{\hidecoords(0,-d)\hfil\hidecoords(w,-d)}}\quad}}
\dp0=0pt

Here's an example of a character that has nonzero width, height, and depth;
it's the left ↑{parenthesis} in ↑{Computer Modern} fonts like |cmr10|.
Computer Modern typefaces are generated by \MF\ programs that involve
lots of parameters, so this example also illustrates the principles of
``↑{meta-design}'': Many different varieties of left parentheses can be
drawn by this one program. But let's focus our attention first on the
comparatively simple way in which the box dimensions are established and
used, before looking into the details of how a meta-parenthesis has
actually been specified. \fixthis % when the dust has settled in new CM...
% probably "tiny" will NOT be zero in cmr10, hence need to redo figs etc
% "thick" here is really "stem" in cm code, but that's probably OK
\begindisplay
|"Left parenthesis"|;\cr
@numeric@ $"ht"\0$, $"dp"\0$;\cr
$"ht"\0="h\_height"\0+"border"\0$;\cr
$.5["ht"\0,-"dp"\0]="axis"\0$;\cr
@beginchar@(|"("|$,7u\0,"ht"\0,"dp"\0)$;\cr
@italcorr@ $"ht"\0\ast"slant"-.5u\0$;\cr
@pickup@ "tinypen";\strut\vadjust{\box0}\cr
$\penpos1("hair"-"tiny",0)$;\cr
$\penpos2(.75["thin","thick"]-"tiny",0)$;\cr
$\penpos3("hair"-"tiny",0)$;\cr
$\mathop{"rt"}x↓{1r}=\mathop{"rt"}x↓{3r}= w-u$; \
 $\mathop{"lft"}x↓{2l}=x↓1-4u$;\cr
$\mathop{"top"}y↓1=h$; \
 $y↓2=.5[y↓1,y↓3]="axis"$;\cr
@filldraw@ $z↓{1l}\{\curl4\}\to z↓{2l}\to\{\curl4\}z↓{3l}\dashto$\cr
↑↑{curl}\qquad $z↓{3r}\{\curl4\}\to z↓{2r}\to\{\curl4\}z↓{1r}\dashto\cycle$;\cr
@penlabels@$(1,2,3)$; \ @endchar@;\cr
\enddisplay

The width of this left parenthesis is $7u\0$, where $u\0$
is an ad hoc parameter that figures in all the widths of the Computer
Modern characters. The height and depth have been calculated in such a way
that the top and bottom of the bounding box are equally distant from an
imaginary line called the {\sl↑{axis}}, which is important in mathematical
typesetting. \ (For example, \TeX\ puts the bar line at the axis
in fractions like $1\over2$; many symbols like `$+$' and `$=$', as well as
parentheses, are centered on the axis line.) \ Our example program puts the
axis midway between the top and bottom of the type by saying that
`$.5["ht"\0,-"dp"\0]="axis"\0$'.  We also place the top at position
`$"ht"\0="h\_height"\0+"border"\0$'\thinspace; here $"h\_height"\0$ is the
height of an~`h', and $"border"\0$ represents an extra amount that will
make the parenthesis slightly taller than any letter.  It turns out that
$"h\_height"\0+"border"\0$ is exactly $7.5"pt"\0$ in |cmr10|, and
$"axis"\0=2.5"pt"\0$; hence $"ht"\0=7.5"pt"\0$ and
$"dp"\0=2.5"pt"\0$, making the parenthesis exactly $10\pt$ tall.

The program for `(' uses a ↑@filldraw@ command, which we haven't
seen before in this book; it's basically a combination of @fill@
and @draw@, where the filling is done with the currently-picked-up pen.
Some of the Computer Modern fonts have characters with ``↑{soft}'' edges
while others have ``↑{crisp}'' edges; the difference is due to the pen that
is used to @filldraw@ the shapes. This pen is a circle whose diameter
is called ↑"tiny"; when "tiny" is fairly large, @filldraw@ will produce
rounded corners, but when $"tiny"=0$ (as it is in |cmr10|) the corners
will be sharp.

The statement `$\penpos1("hair"-"tiny",0)$' makes the breadth of a
simulated broad-edge pen equal to $"hair"-"tiny"$ at position~1; i.e.,
the distance between $z↓{1l}$ and $z↓{1r}$ will be $"hair"-"tiny"$.
We will be filling a region between $z↓{1l}$ and $z↓{1r}$ with a
circle-shaped pen nib whose diameter is "tiny"; the center of that
nib will pass through $z↓{1l}$ and $z↓{1r}$, hence the pen will
effectively add ${1\over2}"tiny"$ to the breadth of the stroke at
either side. The overall breadth at position~1 will therefore be
${1\over2}"tiny"+("hair"-"tiny")+{1\over2}"tiny"\;=\;"hair"$.
(Computer Modern's ``↑{hairline} thickness'' parameter, which governs
the breadth of the thinnest strokes, is called "hair".) \ Similarly,
the statement `$\penpos2(.75["thin","thick"]-"tiny",0)$'  makes the
overall breadth of the pen at position~2 equal to $.75["thin","thick"]$,
which is $3\over4$ of the way between two other parameters that govern
stroke breadths in Computer Modern routines.  If "tiny" is increased while
"hair", "thin", and "thick" stay the same, the effect will simply be to
produce more rounded corners at positions 1 and~3, with little or no effect
on the rest of the shape, provided that "tiny" doesn't get so large that
it exceeds "hair".

\def\paren #1 #2 #3 #4 #5 #6 #7 #8 #9
{\vbox{\dimen0=#3\apspix \hsize=7\dimen0
    \centerline{\tt#1}
    \medskip \kern3pt \kern270\apspix \kern-#4\apspix
    \dimen2=#4\apspix \advance\dimen2 by -#5\apspix
    \figbox{#2}{7\dimen0}{2\dimen2}\vbox
    \kern-2\dimen2 \kern#4\apspix \kern90\apspix \kern-3pt \medskip
    \tabskip 0pt plus 1fil
    \halign to\hsize{$##$\cr
      u=\hfil#3\cr
      "ht"=\hfil#4\cr
      "axis"=\hfil#5\cr
      "tiny"=\hfil#6\cr
      "hair"=\hfil#7\cr
      "thin"=\hfil#8\cr
      "thick"=\hfil#9\cr}}}

Here, for example, are five different left parentheses, drawn by our example
program with various settings of the parameters:
$$\line{\paren cmr10 12a 20 270 90 0 8 9 25
  \hfil\paren cmbx10 12b 23 270 90 0 13 17 41
  \hfil\paren cmvtt10 12c 21 250 110 22 22 25 25
  \hfil\paren cmssdc10 12d 19 270 95 8 23 40 40
  \hfil\paren cmti10 12e 18.4 270 90 8 8 11 23 }$$
Parameter values are shown here in ↑"proof"\kern-1pt\ mode pixel units,
36 to the point. \ (Thus, for example, the value of $u\0$ in |cmr10| is
${20\over36}"pt"\0$.) \ Since |cmbx10| is a ``bold extended'' font,
its unit width~$u$ is slightly larger than the unit width of |cmr10|,
and its pen widths (especially "thick") are significantly larger.
The ``variable-width typewriter'' font |cmvtt10| has soft edges and
strokes of almost uniform thickness, because "tiny" and "hair" are almost
as large as "thin" and "thick". This font also has a raised axis and a smaller
height. An intermediate situation occurs in |cmssdc10|, a ``sans serif
demibold condensed'' font that is similar to the type used in the chapter titles
of this book; $"thick"="thin"$ in this font, but hairlines are noticeably
thinner, and "tiny" provides slightly rounded corners. The ``text italic''
font |cmti10| has rounded ends, and the character shape has been ↑{slanted}
by .25; this means that each point $(x,y)$ has been moved to position
$(x+.25y,y)$, in the path that is filled by @filldraw@.

\danger The vertical line just of the right of the italic left parenthesis
shows the ↑{italic correction} of that character, i.e., the fourth box
dimension mentioned earlier. This quantity was defined by the statement
`↑@italcorr@ $"ht"\0\ast"slant"-.5u\0$' in our program; here ↑"slant" is
a parameter of Computer Modern that is zero in all the unslanted fonts,
but $"slant"=.25$ in the case of |cmti10|. The expression following
@italcorr@ should always be given in sharped units. If the value is
negative, the italic correction will be zero; otherwise the italic
correction will be the stated amount.

\danger The author has obtained satisfactory results by making the italic
correction roughly equal to $.5u$ plus the maximum amount by which the
character sticks out to the right of its box. For example, the top right
end of the left parenthesis will be nearly at position $(w-u,"ht")$ before
slanting, so its $x$~coordinate after slanting will be $w-u+"ht"\ast"slant"$;
this will be the rightmost point of the
character, if we assume that $"slant"\ge0$. Adding $.5u$, subtracting~$w$,
and rewriting in terms of sharped units gives the stated formula. Notice
that when $"slant"=0$ the statement reduces to `@italcorr@ $-.5u\0$';
this means that unslanted left parentheses will have an italic correction
of zero.

\dangerexercise Write a program for right parentheses, to go with these
left parentheses.
\answer The changes are straightforward, except for the italic correction
(for which a rough estimate like the one shown here is good enough):
\begindisplay
|"Right parenthesis"|;\cr
@numeric@ $"ht"\0,"dp"\0$; $"ht"\0="h\_height"\0+"border"\0$;
 $.5["ht"\0,-"dp"\0]="axis"\0$;\cr
@beginchar@(|")"|$,7u\0,"ht"\0,"dp"\0)$;
 \ @italcorr@ $"axis"\0\ast"slant"-.5u\0$;\cr
@pickup@ "tinypen"; \ $\penpos1("hair"-"tiny",0)$;\cr
$\penpos2(.75["thin","thick"]-"tiny",0)$; \ $\penpos3("hair"-"tiny",0)$;\cr
$\mathop{"lft"}x↓{1l}=\mathop{"lft"}x↓{3l}=u$; \
 $\mathop{"rt"}x↓{2r}=x↓1+4u$; \
$\mathop{"top"}y↓1=h$; \
 $y↓2=.5[y↓1,y↓3]="axis"$;\cr
@filldraw@ $z↓{1l}\{\curl4\}\to z↓{2l}\to\{\curl4\}z↓{3l}\dashto$\cr
\qquad $z↓{3r}\{\curl4\}\to z↓{2r}\to\{\curl4\}z↓{1r}\dashto\cycle$;\cr
@penlabels@$(1,2,3)$; \ @endchar@;\cr
\enddisplay
We will see in Chapter xx that it's possible to guarantee perfect symmetry
between left and right parentheses by using picture transformations.

The reader should bear in mind that the conventions of plain \MF\ and of
Computer Modern are not hardwired into the \MF\ language; they are merely
examples of how a person might use the system, and other typefaces may well
be better served by quite different approaches. Our program for left
parentheses makes use of @beginchar@, @endchar@, @italcorr@, @penlabels@,
@pickup@, "penpos", "lft", "rt", "top", "z", and @filldraw@, all of which
are defined somewhat arbitrarily in Appendix~B as part of the plain base;
it also uses the quantities "u", "h\_height", "axis", "tiny", "hair", "thin",
"thick", and "slant", all of which are arbitrary parameters that the author
decided to introduce in his programs for Computer Modern. Once you understand
how to use arbitrary conventions like these, you will be able to modify them
to suit your own purposes.

\exercise (For people who know \TeX.) \ It's fairly clear that the width of
a type box is important for typesetting, but what use does \TeX\ make of
the height and depth?
\answer When horizontal lines are being typeset, \TeX\ keeps track of the
maximum height and maximum depth of all boxes on the line; this determines
whether or not extra space is needed between baselines. The height and depth
are also used to position an accent above or below a character, and to
place symbols in mathematical formulas. Sometimes
boxes are also stacked~up vertically, in which case their heights and depths
are just as important as their widths are for horizontal setting.

\ddanger The primitive commands by which \MF\ actually learns the dimensions
of each box are rarely used directly, since they are intended to be embedded
in higher-level commands like @beginchar@ and @italcorr@. But if you must
know how things are done at the low level, here is the secret: There are
four internal quantities called ↑"charwd", ↑"charht", ↑"chardp", and ↑"charic",
whose values at the time of every ↑@shipout@ command are assumed to be the
box dimensions for the character being shipped out, in units of pt. \ (See
the definitions of @beginchar@ and @italcorr@ in Appendix~B for examples
of how these quantities can be manipulated.)

\ninepoint % all dangerous from here on
\ddanger Besides "charwd" and its cousins, \MF\ also has four other
internal variables whose values are recorded at the time of every
@shipout@:\enddanger

\smallskip\textindent\bull↑"charcode" is rounded to the nearest integer
and then converted to a number between 0 and~255, by adding or subtracting
multiples of~256 if necessary; this ``$c$~code'' is the ↑{location} of the
↑↑{c code} character within its font.

\smallskip\textindent\bull↑"charfam" is rounded to the nearest integer;
the resulting number is a secondary code that can be used to distinguish
between two or more characters with equal $c$ codes. \ (\TeX\ ignores
"charfam" and assumes that each font contains at most 256 characters; but
extensions to \TeX\ for ↑{oriental} languages can use "charfam" to handle
much larger fonts.)

\smallskip\textindent\bull↑"chardx" and "chardy" represent horizontal and
vertical {\sl escapement\/} in units of pixels. \ (Some typesetting
systems use these device-dependent amounts to change their current
position on a page, just after typesetting each character. Other systems,
like the ↑|DVI| software associated with \TeX, assume that $"chardy"=0$
but use "chardx" as the horizontal escapement whenever a horizontal
movement by "chardx" does not cause the subsequent position to ↑{drift}
too far from the device-independent position defined by accumulated
"charwd" values. Plain \MF's @endchar@ routine keeps $"chardy"=0$, but
sets $"chardx":=w$ just before shipping a character to the output.  This
explains why a change to~↑"w" will affect the spacing between adjacent
letters, as discussed earlier.)

\ddanger Two characters with the same $c$ code
should have the same box dimensions and escapements; otherwise
the second character will override the specifications of the first. The boolean
expression `↑{charexists}~$c$' can be used to determine whether or not
a character with a particular $c$~code has already been shipped out.

\danger Let's conclude this chapter by contemplating a \MF\ program that
generates the ``↑{dangerous bend}'' symbol, since that symbol appears so
often in this book. It's a custom-made character intended to be used only at
the very beginnings of paragraphs in which the baselines of the text are
exactly $11\pt$ apart. Therefore it extends below its baseline by $11\pt$;
but it is put into a box of depth zero, because \TeX\ would otherwise
think that the first line of the paragraph contains an extremely deep
character, and this would cause the second line to be moved down.
$$\def\comment{\hfill{\tt\%} }
\halign{\hbox to\hsize{\indent#\hfil}\cr
$"baselinedistance"\0:=11"pt"\0$; \ ↑@define\_pixels@("baselinedistance");\cr
$"heavyline"\0:=50/36"pt"\0$; \ ↑@define\_blacker\_pixels@("heavyline");\cr
$@beginchar@(127,25u\0,"h\_height"\0+"border"\0,0)$; \
 |"Dangerous bend symbol"|;\cr
\pickup @pencircle@ scaled "rulethickness";
 \ $\mathop{"top"}y↓1={25\over27}h$; \ $\mathop{"lft"}x↓4=0$;\cr
$x↓1+x↓1=x↓{1a}+x↓{1b}=x↓{4b}+x↓{2a}=x↓4+x↓2=x↓{4a}+x↓{2b}=x↓{3b}+x↓{3a}=
 x↓3+x↓3=w$;\cr
$x↓{4a}=x↓{4b}=x↓4+u$; \ $x↓{3b}=x↓{1a}=x↓1-2u$;\cr
$y↓4+y↓4=y↓{4a}+y↓{4b}=y↓{3b}+y↓{1a}=y↓3+y↓1=y↓{3a}+y↓{1b}=y↓{2b}+y↓{2a}=
 y↓2+y↓2=0$;\cr
$y↓{1a}=y↓{1b}=y↓1-{2\over27}h$; \ $y↓{4b}=y↓{2a}=
 y↓4+{4\over27}h$;\cr
@draw@ $z↓{1a}\to z↓1\to z↓{1b}\ddashto z↓{2a}\to z↓2\to z↓{2b}\ddashto$\cr
\indent $z↓{3a}\to z↓3\to z↓{3b}\ddashto z↓{4a}\to z↓4\to z↓{4b}
 \ddashto \rm cycle$;\comment the signboard\cr
$x↓{10}=x↓{11}=x↓{12}=x↓{13}=.5w-u$;
 \ $x↓{14}=x↓{15}=x↓{16}=x↓{17}=w-x↓{10}$;\cr
$y↓{10}=y↓{14}=h$; \ $\mathop{"bot"}y↓{13}=-"baselinedistance"$;\cr
$z↓{11}=(z↓{10}\to z↓{13})\;{\rm intersectionpoint}\;
 (z↓{1a}\{z↓{1a}-z↓{4b}\}\to z↓1\{"right"\})$;\cr
$y↓{15}=y↓{11}$; \ $y↓{16}=y↓{12}=-y↓{11}$; \ $y↓{17}=y↓{20}=y↓{21}=y↓{13}$;\cr
@draw@ $z↓{11}\dashto z↓{10}\dashto z↓{14}\dashto z↓{15}$;
 @draw@ $z↓{12}\dashto z↓{13}$;
 @draw@ $z↓{16}\dashto z↓{17}$; \comment the signpost\cr
$x↓{20}=w-x↓{21}$; \ $x↓{21}-x↓{20}=16u$;
 \ @draw@ $z↓{20}\dashto z↓{21}$; \comment ground level\cr
$x↓{36}=w-x↓{31}$; \ $x↓{36}-x↓{31}=8u$;
 \ $x↓{32}=x↓{33}=x↓{36}$; \ $x↓{31}=x↓{34}=x↓{35}$;\cr
$y↓{31}=-y↓{36}={12\over27}h$; \ $y↓{32}=-y↓{35}={9\over27}h$;
 \ $y↓{33}=-y↓{34}={3\over27}h$;\cr
\pickup @pencircle@ scaled "heavyline";\cr
@draw@ $z↓{32}\{z↓{32}-z↓{31}\}\to z↓{33}\ddashto
  z↓{34}\to z↓{35}\{z↓{36}-z↓{35}\}$;
 \comment the dangerous bend\cr
\pickup ↑"razor" xscaled "heavyline"
  ↑{rotated} (↑{angle}$(z↓{32}-z↓{31})+90$);\cr
@draw@ $z↓{31}\dashto z↓{32}$;
 \ @draw@ $z↓{35}\dashto z↓{36}$; \comment upper and lower bars\cr
↑@labels@$(1,1a,1b,2,2a,2b,3,3a,3b,4,4a,4b,10,11,12,13,14,15,16,17,$\cr
\indent$20,21,31,32,33,34,35,36)$; \ @endchar@;\cr
}$$

\setbox0=\vtop{\kern -4pt
  \figbox{12f}{500\apspix}{4.2in}\vbox}
\dp0=0pt
\medbreak

{\tolerance=2000 \hbadness=2000 \spaceskip=.3333em plus .25em minus .12em
\hangindent 515\apspix
\noindent\hbox to 515\apspix{\box0\hfil}%
This program has several noteworthy points of~interest:
(1)~The first parameter to ↑@beginchar@ here is 127, not a
string; this puts the character into font ↑{location}~127. \ (2)~A sequence
of equations like `$a=w-b$; $a'=w-b'$' can conveniently be shortened to
`$a+b=a'+b'=w$'. \ (3)~Three hyphens `$\ddashto$' is an abbreviation for a
line with ``infinite'' tension, ↑↑{---} i.e., an almost straight line that
connects smoothly to its curved neighbors. \ (4)~An `intersectionpoint'
operation finds out where ↑↑{intersectionpoint}
two paths cross; we'll learn more about this in Chapter~14.\par}

\endchapter

A short first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A short
second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Chapter 13. Drawing, Filling,\\and Erasing

The pictures that \MF\ produces are made up of tiny pixels that are either
``on'' or ``off''; therefore you might imagine that the computer works
behind the scenes with some sort of graph paper, and that it darkens some
of the squares whenever you tell it to @draw@ a line or to @fill@ a region.

\newdimen\tinypix \setbox0=\hbox{\sixrm0} \tinypix=5pt
\newdimen\pixcorr \pixcorr=\tinypix \advance\pixcorr by-\wd0
\def\spread#1{\if#1!\let\next\relax\else#1\kern\pixcorr\let\next\spread\fi
  \next}
\def\beginpixdisplay{$$\advance\abovedisplayskip by 2pt
  \advance\belowdisplayskip by-2pt
  \baselineskip=\tinypix
  \halign\bgroup\sixrm\indent\spread##!\hfil\cr}
\MF's internal graph paper is actually more sophisticated than this.
Pixels aren't simply ``on'' or ``off'' when \MF\ is working on a picture,
they can be ``doubly on'' or ``triply off.'' Each pixel contains a
small {\sl integer\/} value, and when a character is finally shipped out
to a font the black pixels are those whose value is greater than zero.
For example, the two commands
\begindisplay
↑@fill@ $(0,3)\dashto(9,3)\dashto(9,6)\dashto(0,6)\dashto\cycle$;\cr
@fill@ $(3,0)\dashto(3,9)\dashto(6,9)\dashto(6,0)\dashto\cycle$
\enddisplay
yield the following $9\times9$ pattern of pixel values:
\beginpixdisplay
000111000\cr
000111000\cr
000111000\cr
111222111\cr
111222111\cr
111222111\cr
000111000\cr
000111000\cr
000111000\cr
\enddisplay
Pixels that have been filled twice now have a value of 2.

When a simple region is ``filled,'' its pixel values are all increased by~1;
when it is ``unfilled,'' they are all decreased by~1. The command
\begindisplay
↑@unfill@ $(1,4)\dashto(8,4)\dashto(8,5)\dashto(1,5)\dashto\cycle$
\enddisplay
will therefore change the pattern above to
\beginpixdisplay
000111000\cr
000111000\cr
000111000\cr
111222111\cr
100111001\cr
111222111\cr
000111000\cr
000111000\cr
000111000\cr
\enddisplay
The pixels in the center have not been erased (i.e., they will still be
black if this picture is output to a font), because they still have a
positive value.

Incidentally, this example illustrates the fact that the edges between
\MF's pixels are lines that have integer ↑{coordinates}, just as the
squares on graph paper do. For example, the lower left `{\sixrm0}' in
the $9\times9$ array above corresponds to the pixel whose boundary is
`$(0,0)\dashto(1,0)\dashto(1,1)\dashto(0,1)\dashto\cycle$'. The $(x,y)$
coordinates of the points inside this pixel lie between 0 and~1.

\exercise What are the $(x,y)$ coordinates of the four corners of the
{\sl middle\/} pixel in the $9\times9$ array?
\answer $(4,4)$, $(4,5)$, $(5,5)$, $(5,4)$. \ (Therefore the command
\begindisplay
@unfill@ $(4,4)\dashto(4,5)\dashto(5,5)\dashto(5,4)\dashto\cycle$
\enddisplay
will decrease the value of this pixel by 1.)

\exercise What picture would have been obtained if the @unfill@ command
had been given {\sl before\/} the two @fill@ commands in the examples
above?
\answer The result would be exactly the same; @fill@ and @unfill@ commands
can be given in any order. \ (After an initial @unfill@ command, some
pixel values will be $-1$, the others will be zero.)

\exercise Devise an @unfill@ command that will produce the pixel values
\beginpixdisplay
000111000\cr
000101000\cr
000101000\cr
111212111\cr
100101001\cr
111212111\cr
000101000\cr
000101000\cr
000111000\cr
\enddisplay
when it is used just after the @fill@ and @unfill@ commands already given.
\answer @unfill@ $(4,1)\dashto(4,8)\dashto(5,8)\dashto(5,1)\dashto\cycle$.

A ``simple'' region is one whose boundary does not intersect itself; more
complicated effects occur when the boundary lines cross. For example,
\begindisplay
@fill@ $(0,1)\dashto(9,1)\dashto(9,4)\dashto(4,4)\dashto$\cr
\indent$(4,0)\dashto(6,0)\dashto
 (6,3)\dashto(8,3)\dashto(8,2)\dashto(0,2)\dashto\cycle$\cr
\enddisplay
produces the pixel pattern
\beginpixdisplay
000011111\cr
000011001\cr
111122111\cr
000011000\cr
\enddisplay
Notice that some pixels receive the value 2, because they're ``↑{doubly
filled}.'' There's also a ``↑{hole}'' where the pixel values remain zero,
even though they are surrounded by filled pixels; the pixels in that hole
are not considered to be in the region, but the doubly filled pixels
are considered to be in the region twice.

\exercise Show that the first $9\times9$ cross pattern on the previous
page can be generated by a single @fill@ command. \ (The nine pixel
values in the center should be~2, as if two separate regions had been
filled, even though you are doing only one @fill@.)
\answer Here are two of the many solutions:
\begindisplay
@fill@ $(0,3)\dashto(9,3)\dashto(9,6)\dashto(6,6)\dashto(6,9)\dashto$\cr
\indent $(3,9)\dashto(3,0)\dashto(6,0)\dashto(6,6)\dashto(0,6)\dashto\cycle$;\cr
@fill@ $(0,3)\dashto(9,3)\dashto(9,6)\dashto(0,6)\dashto(0,3)\dashto$\cr
\indent $(3,3)\dashto(3,0)\dashto(6,0)\dashto(6,9)\dashto(3,9)\dashto
  (3,3)\dashto\cycle$.\cr
\enddisplay
(It turns out that {\sl any\/} pixel pattern can be obtained by a single,
sufficiently hairy @fill@ command. But unnatural commands are usually also
inefficient and unreadable.)

\exercise What do you think is the result of `@fill@ $(0,0)\dashto(1,0)\dashto
(1,1)\dashto(0,1)\dashto(0,0)\dashto(1,0)\dashto(1,1)\dashto(0,1)\dashto
\cycle$'\thinspace?
\answer The value of the enclosed pixel is increased by 2. \ (We'll see later
that there's a simpler way to do this.)

A @fill@ command can produce even stranger effects when its boundary lines
cross in only one place. If you say, for example,
\begindisplay
@fill@ $(0,2)\dashto(4,2)\dashto(4,4)\dashto(2,4)\dashto(2,0)
 \dashto(0,0)\dashto\cycle$
\enddisplay
\MF\ will produce the $4\times4$ pattern
\setbox0=\hbox to\tinypix{\hss
  $\scriptscriptstyle{\hbox to3pt{}\over}$\hss\kern\pixcorr}
\dp0=0pt
\beginpixdisplay
0011\cr
0011\cr
!\copy0\copy0 \spread00\cr
!\copy0\copy0 \spread00\cr
\enddisplay
where `$\hbox to3pt{}\over$' stands for the value $-1$. Furthermore the
machine will report that you have a ``↑{strange path}'' whose ``↑{turning
number}'' is zero!  What does this mean? Basically, it means that your
path loops around on itself something like a figure~8; this causes a
breakdown in \MF's usual rules for distinguishing the ``inside'' and
``outside'' of a curve.

\danger Every cyclic path has a {\sl turning number\/} that can be understood
as follows. Imagine that you are driving a car along the path and that you
have a digital compass that tells in what direction you're heading. For
example, if the path is
\begindisplay
$(0,0)\dashto(2,0)\dashto(2,2)\dashto(0,2)\dashto\cycle$
\enddisplay
you begin driving in direction $0↑\circ$, then you make four left turns.
After the first turn, your compass heading is $90↑\circ$; after the
second, it is $180↑\circ$; and after the third it is $270↑\circ$. \ (The
compass direction increases when you turn left and decreases when you turn
right; therefore it now reads $270↑\circ$, not $-90↑\circ$.) \ At the
end of this cycle the compass will read $360↑\circ$, and if you go around
again the reading will be $720↑\circ$. Similarly, if you had traversed the
path
\begindisplay
$(0,0)\dashto(0,2)\dashto(2,2)\dashto(2,0)\dashto\cycle$
\enddisplay
(which is essentially the same, but in the opposite direction), your compass
heading would have started at $90↑\circ$ and ended at $-270↑\circ$;
in this case each circuit would have {\sl decreased\/} the reading
by~$360↑\circ$. It is clear that a drive around any cyclic path will
change the compass heading by some multiple of~$360↑\circ$, since you
end in the same direction you started. The turning number of a path is
defined to be $t$ if the compass heading changes by exactly $t$~times
$360↑\circ$ when the path is traversed. Thus the two example cycles we have
just discussed have turning numbers of $+1$ and $-1$, respectively; and
the ``strange path'' on the previous page that produced both positive and
negative pixel values does indeed have a turning number of~0.

\danger Here's how \MF\ actually implements a @fill@ command, assuming that
the cyclic path being filled has a {\sl positive\/} turning number:
The path is first ``digitized,'' if necessary, so that it lies entirely on
the edges of pixels; in other words, it is distorted slightly so that it
is confined to the lines between pixels on graph paper. \ (Our examples so
far in this chapter have not needed any such adjustments.) \ Then each
individual pixel value is increased by~$j$ and decreased by~$k$ if an
infinite horizontal line to the left of that pixel intersects the
digitized path $j$~times when the path is traveling downward and $k$~times
when it is traveling upward. For example, let's look more closely at the
non-simple path on the previous page that enclosed a hole:
$$\def\\#1{\hbox to 11pt{\hss$#1$\hss}}
\def\up{\hbox to0pt{\hss\lower3pt\vbox to 11pt{
      \hbox{\tenex\char'77}\vss\hbox{\tenex\char'170}\kern0pt}\hss}}
\def\down{\hbox to0pt{\hss\lower3pt\vbox to 11pt{
      \hbox{\tenex\char'171}\vss\hbox{\tenex\char'77}\kern0pt}\hss}}
\def\under{\smash{\rlap{\lower3.2pt\vbox{\hrule width 11pt}}}}
\def\over{\smash{\rlap{\raise7.8pt\vbox{\hrule width 11pt}}}}
\halign{\indent#\cr
\\a\\a\\a\\a\over\down\\b\over\\b\over\under\\b\over\under\\b\over\\b\up\cr
\under\\a\under\\a\under\\a\under\\a\down\under\\b\under\\b\up
 \under\\c\under\\c\down\\d\up\cr
\down\under\\e\under\\e\under\\e\under\\e\down\under\\f\under\\f\up
 \under\\g\under\\g\under\\g\up\cr
\\a\\a\\a\\a\down\under\\b\under\\b\up\\h\\h\\h\cr}$$
Pixel $d$ has $j=2$ descending edges and $k=1$ ascending edges to its left,
so its net value increases by $j-k=1$; pixels~$g$ are similar.
Pixels~$c$ have $j=k=1$, so they lie in a ``hole'' that is unfilled;
pixels~$f$ have $j=2$ and $k=0$, so they are doubly filled. This rule
works because, intuitively, the inside of a region lies at the {\sl left\/}
of a path whose turning number is positive.

\dangerexercise True or false: When the turning number of a cyclic path is
positive, a @fill@ command increases each individual pixel value by $l-m$,
if an infinite horizontal line to the {\sl right\/} of that pixel intersects
the digitized path $l$~times when the path is traveling upward and $m$~times
when it is traveling downward. \ (For example, pixels~$e$ have $l=2$ and
$m=1$; pixels~$c$ have $l=m=1$.)
\answer True; $j-k=l-m$, since $k+l=j+m$. \ (What comes up must go down.)

\danger When the turning number is negative, a similar rule applies,
except that the pixel values are {\sl decreased\/} by~$j$ and {\sl
increased\/} by~$k$; in this case the inside of the region lies at the
{\sl right\/} of the path.

\danger But when the turning number is zero, the inside of the region
lies sometimes at the left, sometimes at the right. \MF\ uses the rule
for positive turning number and reports that the path is ``strange.''
You can avoid this error message by setting `$"turningcheck":=0$';
↑↑"turningcheck" in this case the rule for positive turning number is
always used for filling, even when the turning number is negative.

Plain \MF's ↑@draw@ command is different from @fill@ in two important ways.
First, it uses the currently-picked-up pen, thereby ``thickening'' the path.
Second, it does not require that the path be cyclic. There is also a third
difference, which needs to be mentioned although it is not quite as important:
A @draw@ command may increase the value of certain pixels by more than~1,
even if the shape being drawn is fairly simple. For example, the pixel pattern
{\parindent=0pt
\beginpixdisplay
0000000000000000000000000000000000000000000000000000000000000000000000\cr
0000001111122222111110000000000000000000000000011111111000000000000000\cr
0000111111111211111111100000000000000000000011111111111111000000000000\cr
0001111111111011111111110000000000000000001111111111111111110000000000\cr
0001111111111011111111110000000000000000111111111111111111111100000000\cr
0011111111110001111111111000000000000001111111111111111111111110000000\cr
0011111111110001111111111000000000000011111111111111111111111111000000\cr
0011111111110001111111111000000000000111111111111111111111111111100000\cr
0111111111100000111111111100000000001111111111111111111111111111110000\cr
0111111111100000111111111100000000001111111111111111111111111111110000\cr
0111111111100000111111111100000000011111111111111111111111111111111000\cr
0111111111100000111111111100000000011111111111111111111111111111111000\cr
0111111111100000111111111100000000111111111111111112111111111111111100\cr
0111111111100000111111111100000000111111111111111112111111111111111100\cr
0111111111100000111111111100000001111111111111111122111111111111111110\cr
0111111111100000111111111100000001111111111111211121111211111111111110\cr
0111111111100000111111111100000001111111111111112122221111111111111110\cr
0111111111100000111111111100000001111111111111111100111111111111111110\cr
0111111111100000111111111100000001111111111111112000011111111111111110\cr
0111111111100000111111111100000001111111111112211000011211111111111110\cr
0111111111100000111111111100000000111111111111110000001111111111111100\cr
0111111111100000111111111100000000111111111111110000001111111111111100\cr
0111111111100000111111111100000000011111111111100000000111111111111000\cr
0111111111100000111111111100000000001111111111000000000011111111110000\cr
0111111111100000111111111100000000000011111100000000000000111111000000\cr
0000000000000000000000000000000000000000000000000000000000000000000000\cr
\enddisplay}%
was produced by two @draw@ commands. The left-hand shape came from
\begindisplay
\pickup ↑"razor" scaled 10; \ @draw@ $(6,1)\{"up"\}\mskip-3mu
 \to(13.5,25)\to\mskip-3mu\{"down"\}(21,1)$;
\enddisplay
it's not difficult to imagine why some of the top pixels get the value~2
here because an actual razor-thin pen would cover those pixels twice as it
follows the given path. But the right-hand shape, which came from
\begindisplay
\pickup @pencircle@ scaled 16; \ @draw@ $(41,9)\to(51,17)\to(61,9)$
\enddisplay
is harder to explain; there seems to be no rhyme or reason to the pattern
of 2's in that case. \MF's method for drawing curves with thick pens is
too complicated to explain here, so we shall just regard it as a curious
process that occasionally shoots out extra spurts of ink in the interior
of the shape that it's filling. Sometimes a pixel value even gets as high
as 3~or more; but if we ignore such anomalies and simply consider the set
of pixels that receive a positive value, we find that a reasonable shape
has been drawn.

The left-parenthesis example in Chapter 12 illustrates the ↑@filldraw@
command, which is like @fill@ in that it requires a cyclic path, and like
@draw@ in that it uses the current pen. Pixel values are increased inside
the region that you would obtain by drawing the specified path with the current
pen and then filling in the interior. Some of the pixel values in this
region may increase by 2~or more.  The turning number of the path
should be nonzero.

Besides @fill@, @draw@, and @filldraw@, you can also say `↑@drawdot@',
as illustrated at the beginning of Chapter~5. In this case you should specify
only a single point; the currently-picked-up pen will be used to increase
pixel values by~1 around that point. Chapter~xx explains that this gives
slightly better results than if you were to draw a one-point path.

\danger There's also an ↑@undraw@ command, analogous to @unfill@; it
decreases pixel values by the same amount that @draw@ would increase them.
Furthermore---as you might expect---↑@unfilldraw@ and ↑@undrawdot@ are the
respective opposites of @filldraw@ and @drawdot@.

\danger If you try to use @unfill@ and/or @undraw@ in connection with
@fill@ and/or @draw@, you'll soon discover that something else is
necessary. Plain \MF\ has a ↑@cullit@ command that replaces all
negative pixel values by~0 and all positive pixel values by~1. This
``↑{culling}'' operation makes it possible to erase unwanted sections
of a picture in spite of the vagaries of @draw@ and @undraw@, and in spite of
the fact that overlapping regions may be doubly filled.

\danger The command `↑@erase@ @fill@ $c$' is an abbrevation for
`@cullit@; @unfill@~$c$; @cullit@'; this zeros out the pixel values inside
the cyclic path~$c$, and sets other pixel values to~1 if they were positive
before erasing took place. \ (It works because the initial @cullit@ makes
all the values 0 or~1, then the @unfill@ changes the values inside~$c$
to 0 or negative. The final @cullit@ gets rid of the negative values,
so that they won't detract from future filling and drawing.) \ You can
also use `@draw@', `@filldraw@', or `@drawdot@' with `@erase@'; for example,
`@erase@ @draw@~$p$' is an abbreviation for `@cullit@; @undraw@~$p$;
@cullit@', which uses the currently-picked-up pen as if it were an
eraser applied to path~$p$.

{\ninepoint
\medbreak
\parshape 7 3pc 17pc 3pc 17pc
0pc 20pc 0pc 20pc 0pc 20pc 0pc 20pc 0pc 29pc
\noindent
\hbox to0pt{\hskip-3pc\dbend\hfill}
\rightfig 13a ({166.66667\apspix} x {133.33333\apspix}) ↑9pt
The cube at the right of this paragraph illustrates one of the effects that
is easily obtained by erasing. First the eight points are defined, and
the ``back'' square is drawn; then two lines of the ``front'' square are
erased, using a somewhat thicker pen; finally the remaining lines are
drawn with the ordinary pen:
\begindisplay
$s\0:=5"pt"\0$; \ @define\_pixels@$(s)$; \ |%| side of the square\cr
$z↓1=(0,0)$; \ $z↓2=(s,0)$; \ $z↓3=(0,s)$; $z↓4=(s,s)$;\cr
↑@for@ $k=1$ @upto@ 4: $z↓{k+4}=z↓k+({2\over3}s,{1\over3}s)$; \ @endfor@\cr
\pickup @pencircle@ scaled $.4"pt"$; \
@draw@ $z↓5\dashto z↓6\dashto z↓8\dashto z↓7\dashto \cycle$;\cr
\pickup @pencircle@ scaled $1.6"pt"$; \
@erase@ @draw@ $z↓2\dashto z↓4\dashto z↓3$;\cr
\pickup @pencircle@ scaled $.4"pt"$; \
@draw@ $z↓1\dashto z↓2\dashto z↓4\dashto z↓3\dashto \cycle$;\cr
@for@ $k=1$ @upto@ 4: @draw@ $z↓k\dashto z↓{k+4}$; \ @endfor@.\cr
\enddisplay
At its true size the resulting ↑{cube} looks like this:
`\thinspace{\manual\cubea}\thinspace'.\par}

\dangerexercise Modify the construction in the preceding paragraph so
that you get the {\sl↑{impossible cube}\/}
`\thinspace{\manual\cubeb}\thinspace' instead.
\answer The tricky part is to remember that `@erase@ @draw@ $z↓i\dashto z↓j$'
will erase pixels near $z↓i$ and $z↓j$. Therefore if $z↓3\dashto z↓4$ is
drawn before $z↓4\dashto z↓2$, we can't erase $z↓4\dashto z↓2$ without losing
some of $z↓3\dashto z↓4$; it's necessary to erase only part of one line.
One way to solve the problem is to do the following, after defining the
points and picking up the pen as before:
\begindisplay
@draw@ $z↓3\dashto z↓4$; \ @draw@ $z↓5\dashto z↓6$;\cr
↑@cullit@; \ \pickup @pencircle@ scaled $1.6"pt"$;\cr
↑@undraw@ $z↓7\dashto {1\over2}[z↓7,z↓5]$; \
 @undraw@ $z↓2\dashto {1\over2}[z↓2,z↓4]$;\cr
@cullit@; \ \pickup @pencircle@ scaled $.4"pt"$;\cr
@draw@ $z↓3\dashto z↓1\dashto z↓2\dashto z↓4$; \
 @draw@ $z↓5\dashto z↓7\dashto z↓8\dashto z↓6$;\cr
@for@ $k=1$ @upto@ 4: \ @draw@ $z↓k\dashto z↓{k+4}$; \ @endfor@.\cr
\enddisplay
(Note that it would not be quite enough to erase only from $z↓7$ to
${1\over3}[z↓7,z↓5]$!)\par
It's also possible to solve this problem without partial erasing, if we
use additional features of \MF\ that haven't been explained yet. Let's
consider only the job of drawing $z↓7\dashto z↓5\dashto z↓6$ and
$z↓3\dashto z↓4\dashto z↓2$, since the other eight lines can easily be
added later. Alternative Solution~1 uses picture operations:
\begindisplay
@pen@ "eraser"; \ $"eraser"=@pencircle@$ scaled $1.6"pt"$;\cr
@draw@ $z↓3\dashto z↓4$; \
@erase@ @draw@ $z↓7\dashto z↓5$ ↑@withpen@ "eraser"; \
@draw@ $z↓7\dashto z↓5$;\cr
@picture@ "savedpicture"; \ $"savedpicture"="currentpicture"$; \ ↑@clearit@;\cr
@draw@ $z↓6\dashto z↓5$; \
@erase@ @draw@ $z↓2\dashto z↓4$ ↑@withpen@ "eraser"; \
@draw@ $z↓2\dashto z↓4$;\cr
↑@addto@ "currentpicture" @also@ "savedpicture".\cr
\enddisplay
Alternative Solution 2 is trickier, but still instructive; it uses
`↑@withweight@' options and the fact that @draw@ does not increase any
pixel values by more than the stated weight when the path is a straight
line:
\begindisplay
@draw@ $z↓3\dashto z↓4$; \
↑@undraw@ $z↓7\dashto z↓5$ @withpen@ "eraser";\cr
@draw@ $z↓7\dashto z↓5$ @withweight@ 2; \
↑@cullit@ @withweight@ 2;\cr
@draw@ $z↓6\dashto z↓5$; \
↑@undraw@ $z↓2\dashto z↓4$ @withpen@ "eraser";\cr
@draw@ $z↓2\dashto z↓4$ @withweight@ 2;\cr
\enddisplay
(These alternative solutions were suggested by Bruce ↑{Leban}.)

\dangerexercise Write a \MF\ program to produce the symbol
`{\manual\bicentennial}'. \ [{\sl Hints:\/} The character is $10\pt$
wide, $7\pt$ high, and $2\pt$ deep. The starlike path can be defined by
five points connected by ``tense'' lines as follows:
\begindisplay
@pair@ "center"; \ $"center"=(.5w,2"pt")$;\cr
@numeric@ "radius"; \ $"radius"=5"pt"$;\cr
@for@ $k=0$ @upto@ 4: \ $z↓k="center"+("radius",0)$
  ↑{rotated}$(90+{360\over5}k)$; \ @endfor@\cr
@def@ :: = ↑↑{tension} $\to\tension 5\to$ @enddef@;\cr
@path@ "star"; \  $"star"=z↓0::z↓2::z↓4::z↓1::z↓3::\cycle$;\cr
\enddisplay
You probably want to work with ↑{subpaths} of ↑"star" instead of drawing the
whole path at once, in order to give the illusion that the curves cross over
and under each other.]
\answer Here's an analog of the first solution to the previous
exercise:
\begindisplay
@beginchar@(|"*"|$,10"pt"\0,7"pt"\0,2"pt"\0)$;\cr
@pair@ "center"; \dots  \<as in the hint>\cr
\pickup @pencircle@ scaled $.4"pt"$; \ @draw@ "star";\cr
@cullit@; \ \pickup @pencircle@ scaled $1.6"pt"$;\cr
@for@ $k=0$ @upto@ 4: \ @undraw@ subpath$(k+.55,k+.7)$ @of@ "star"; \ @endfor@\cr
@cullit@; \ \pickup @pencircle@ scaled $.4"pt"$;\cr
@for@ $k=0$ @upto@ 4: \ @draw@ subpath$(k+.47,k+.8)$ @of@ "star"; \ @endfor@\cr
@labels@(0,1,2,3,4); \ @endchar@.\cr
\enddisplay
However, as in the previous case, there's an Alternate Solution~1
by Bruce ↑{Leban} that is preferable because it doesn't depend
on magic constants like .55 and~.47:
\begindisplay
@beginchar@ $\ldots$ \<as above> $\ldots$ scaled $.4"pt"$;\cr
@picture@ "savedpicture"; \ $"savedpicture"="nullpicture"$;\cr
@pen@ "eraser"; \ $"eraser":=@pencircle@$ scaled $1.6"pt"$;\cr
@for@ $k=0$ @upto@ 4:\cr
\indent @draw@ subpath$(k,k+1)$ @of@ "star"; @cullit@;\cr
\indent @undraw@ subpath$(k+3,k+4)$ @of@ "star" @withpen@ "eraser"; @cullit@;\cr
\indent @addto@ "savedpicture" @also@ "currentpicture"; @clearit@; @endfor@\cr
$"currentpicture":="savedpicture"$; \ @labels@(0,1,2,3,4); \ @endchar@.\cr
\enddisplay

\dangerexercise What does the command `@fill@ "star"' do, if "star" is the
path defined above?
\answer It increases pixel values by 1 in the five lobes of the star, and by~2
in the central pentagon-like region.

\decreasehsize 6pc
\dangerexercise Devise a ↑{macro} called `↑@overdraw@' such that the command
\rightfig 13aa (50pt x 100pt) ↑11pt
`@overdraw@~$c$' will erase the inside of region~$c$ and will then draw the
boundary of~$c$ with the currently-picked-up pen, assuming that $c$~is a
cyclic path that doesn't intersect itself. \ (Your macro could be used, for
example, in the program
\begindisplay
@path@ $S$; \ $S=((0,1)\to(2,0)\to(4,2)\to$\cr
\indent$(2,5.5)\to(0,8)\to(2,10)\to(3.5,9))$ scaled $9"pt"$;\cr
@for@ $k=0$ @upto@ 35: @overdraw@ ↑"fullcircle" scaled 3"mm"\cr
\indent shifted ↑{point} $k/35\ast \mathop{\rm length} S$ @of@ $S$;
 @endfor@\cr
\enddisplay
to create the curious ↑{S} shown here.)
\answer @def@ @overdraw@ @expr@ $c$ = @erase@ @fill@ $c$; @draw@ $c$ @enddef@.

\restorehsize
\ddangerexercise The ↑{M\"obius} Watchband Corporation has a logo that
looks like this:
\displayfig 13bb (.5in)
Explain how to produce it (or something very similar) with \MF.
\answer First we need to generalize the ↑@overdraw@ macro of the previous
exercise so that it applies to arbitrary cycles~$c$, even those that are
self-intersecting:
\begindisplay
@def@ @overdraw@ @expr@ $c$ = ↑@begingroup@\cr
\indent@picture@ "region"; $"region":="nullpicture"$;\cr
\indent↑@interim@ $"turningcheck":=0$; ↑@addto@ "region" @contour@ $c$;\cr
\indent↑@cull@ "region" @dropping@ $(0,0)$;\cr
\indent↑@cullit@; @addto@ "currentpicture" ↑@also@ $-"region"$; @cullit@;\cr
\indent@draw@ $c$ ↑@endgroup@ @enddef@;\cr
\enddisplay
(This code uses operations defined later in this chapter; it erases the
"region" of pixels that would be made nonzero by the command `@fill@~$c$'.)
\ The watchband is now formed by overdrawing its links, one at a time,
doing first the ones that are underneath:
\begindisplay
@beginchar@$("M",1.25"in"\0,.5"in"\0,0)$;\cr
\pickup @pencircle@ scaled .4"pt";\cr
$z↓1=(20,-13)$; \ $z↓2=(30,-6)$; \ $z↓3=(20,1)$; $z↓4=(4,-7)$;\cr
\indent $z↓5=(-12,-13)$; \ $z↓6=(-24,-4)$; \ $z↓7=(-15,6)$;\cr
@path@ $M$; $M=("origin"\to z1\to z2\to z3\to z4\to z5\to z6\to z7\to$\cr
\indent$"origin"\to -z7\to -z6\to -z5\to -z4\to -z3\to -z2\to -z1\to\cycle)$\cr
↑↑"origin" \indent\indent scaled $(h/26)$ shifted $(.5w,.5h)$;\cr
@def@ @link@(@expr@ $n$) =\cr
\indent @overdraw@ subpath ${1\over3}(n,n+1)$ of $M\;\dashto$\cr
\indent\indent	subpath ${1\over3}(n+25,n+24)$ of $M\;\dashto\;\cycle\;$
 @enddef@;\cr
@for@ $k=1$ @upto@ 12: @link@$(k+11)$; @link@$(12-k)$; @endfor@
@endchar@;\cr
\enddisplay

\danger Chapter 7 points out that variables can be of type `↑@picture@',
and Chapter~8 mentions that expressions can be of type `@picture@', but
we still haven't seen any examples of picture variables or picture
expressions. Plain \MF\ keeps the currently-worked-on picture in a
picture variable called ↑"currentpicture", and you can copy it by
equating it to a picture variable of your own. For example, if you
say `@picture@ $v[\,]$' at the beginning of your program, you can write
equations like
\begindisplay
$v↓1="currentpicture"$;
\enddisplay
this makes $v↓1$ equal to the picture that has been drawn so far; i.e.,
it gives $v↓1$ the same array of pixel values that "currentpicture" now has.

\begingroup\def\dbend{{\manual\char0}} % reverse-video dangerous bend sign
\danger Pictures can be added or subtracted; for example, $v↓1+v↓2$
↑↑{sum of pictures} ↑↑{negative of a picture} ↑↑{inverse video}
stands for the picture whose pixel values are the sums of the pixel
values of $v↓1$ and~$v↓2$. The ``↑{reverse-video} ↑{dangerous bend}'' sign that
heads this paragraph was made by substituting the following code for
the `@endchar@' in the program at the end of Chapter~12:
\begindisplay
@picture@ "dbend"; \ $"dbend"="currentpicture"$;\cr
@endchar@; \ |%| end of the normal dangerous bend sign\cr
@beginchar@$(0,25u\0,"h\_height"\0+"border"\0,0)$;\cr
@fill@ $(0,-11"pt")\dashto(w,-11"pt")\dashto(w,h)\dashto(0,h)\dashto\cycle$;\cr
$"currentpicture":="currentpicture"-"dbend"$;\cr
@endchar@;\ |%| end of the reversed dangerous bend sign\cr
\enddisplay
↑↑{black/white reversal} The pixel values in "dbend" are all zero or more;
thus the pixels with a positive value, after "dbend" has been subtracted from
a filled rectangle, will be those that are inside the rectangle
but zero in "dbend".

\endgroup % back to normal \dbend

\danger We will see in Chapter xx that pictures can also be shifted,
reflected, and rotated by multiples of $90↑\circ$. For example,
the statement `$"currentpicture":="currentpicture"$~shifted~3"right"'
shifts the entire current picture three pixels to the right.

\danger There's a ``constant'' picture called ↑"nullpicture", whose pixel
values are all zero;
plain \MF\ defines `↑@clearit@' to be an abbreviation for the
assignment `"currentpicture:=nullpicture"'. The current picture is
cleared automatically by every ↑@beginchar@ and ↑@mode\_setup@ command,
so you usually don't have to say `@clearit@' in your own programs.

\danger Here's the formal syntax for picture expressions. Although \MF\ has
comparatively few built-in operations that deal with entire pictures,
the operations that do exist have the same syntax as the similar operations
we have seen applied to numbers and pairs.
\beginsyntax
<picture primary>\is<picture variable>
 \alt\thinspace"nullpicture"
 \alt[(]<picture expression>[)]
 \alt<plus or minus><picture primary>
<picture secondary>\is<picture primary>
 \alt<picture secondary><transformer>
<picture tertiary>\is<picture secondary>
 \alt<picture tertiary><plus or minus><picture secondary>
<picture expression>\is<picture tertiary>
\endsyntax

\danger The ``total weight'' of a picture is the sum of all its pixel
values, divided by 65536; you can compute this numeric quantity by
saying
\begindisplay
↑{totalweight}\<picture primary>.
\enddisplay
\MF\ divides by 65536 in order to avoid overflow in case of huge pictures.
If the totalweight function returns a number whose absolute
value is less than~.5, as it usually is, you can safely divide that number
by ↑"epsilon" to obtain the integer sum of all pixel values.

\ddanger Let's turn to the computer again and try to evaluate some simple
picture expressions interactively, using the general routine |expr.mf|
of Chapter~8. When \MF\ says `|gimme|', you can type
\begintt
hide(fill unitsquare) currentpicture
\endtt
and the machine will respond as follows:
\begintt
>> Edge structure at line 5:
row 0: 0+ 1- ||
\endtt
What does this mean? Well, `↑@hide@' is plain \MF's sneaky way to insert
a command or sequence of commands into the middle of an expression; such
commands are executed before the rest of the expression is looked at. In
this case the command `@fill@ "unitsquare"' sets one pixel value of the
current picture to~1, because ↑"unitsquare" is plain \MF's abbreviation
for the path $(0,0)\dashto(1,0)\dashto(1,1)\dashto(0,1)\dashto\cycle$. The
value of "currentpicture" is displayed as `|row|~|0:| |0+|~|1-|', because
this means
``in row~0, the pixel value increases at $x=0$ and decreases at $x=1$.''

\ddanger \MF\ represents pictures internally by remembering only the vertical
↑{edges} where pixel values change. For example, the picture just displayed
has just two edges, both in row~0, i.e., both in the row between $y$~coordinates
0 and~1. \ (Row~$k$ contains vertical edges whose $x$~coordinates are integers
and whose $y$~coordinates run between $k$ and $k+1$.) \ The fact that edges
are represented, rather than entire arrays of pixels, makes it possible for
\MF\ to operate efficiently at high resolutions, because the number of edges
in a picture is essentially proportional to the ↑{resolution} while the total
number of pixels is proportional to the resolution {\sl squared}. A ten-fold
increase in resolution therefore calls for only a ten-fold (rather than a
hundred-fold) increase in memory space and execution time.

\def\pixpat#1#2#3#4{\vcenter{\sixrm\baselineskip=\tinypix
  \hbox{#1\kern\pixcorr#2}\hbox{#3\kern\pixcorr#4}}}
\ddanger Continuing our computer experiments, let's declare a picture variable
and fill a few more pixels:
\begintt
hide(picture V; fill unitsquare scaled 2; V=currentpicture) V
\endtt
The resulting picture has pixel values $\pixpat1121\,$,
and its edges are shown thus:
\begintt
>> Edge structure at line 5:
row 1: 0+ 2- ||
row 0: 0+ 2- 0+ 1- ||
\endtt
If we now type `|-V|', the result is similar but with the signs changed:
\begintt
>> Edge structure at line 5:
row 1: 0- 2+ ||
row 0: 0- 2+ 0- 1+ ||
\endtt
(You should be doing the experiments as you read this.) \ A more interesting
picture transformation occurs if we ask for `|V|~|rotated-90|'; the picture
$\pixpat2111$ appears below the baseline, hence the following edges are shown:
\begintt
>> Edge structure at line 5:
row -1: || 0++ 1- 2-
row -2: || 0+ 2-
\endtt
Here `↑|++|' denotes an edge where the weight increases by 2. The edges appear
↑↑|+++| {\sl after\/} ↑{vertical line}s `\|' in this case, while they appeared
{\sl before\/} vertical lines in the previous examples; this means that \MF\
has sorted the edges by their $x$~coordinates. Each @fill@ or @draw@ instruction
contributes new edges to a picture, and unsorted edges accumulate until
\MF\ needs to look at them in left-to-right order. \ (Type
\begintt
V rotated-90 rotated 90
\endtt
to see what $V$ itself looks like when its edges have been sorted.) \ The
expression
\begintt
V +  V rotated 90 shifted 2right
\endtt
produces an edge structure with both sorted and unsorted edges:
\begintt
>> Edge structure at line 5:
row 1: 0+ 2- || 0+ 2-
row 0: 0+ 2- 0+ 1- || 0+ 1+ 2--
\endtt
In general, addition of pictures is accomplished by simply combining the
unsorted and sorted edges of each row separately.

\ddangerexercise Guess what will happen if you type `|hide(cullit)|
|currentpicture|' now; and verify your guess by actually doing the experiment.
\answer The pixel pattern $\pixpat1121$ is culled to $\pixpat1111\,$,
and \MF\ needs to sort the edges as it does this; so the result is simply
\begintt
row 1: || 0+ 2-
row 0: || 0+ 2-
\endtt

\ddangerexercise Guess (and verify) what will happen when you type the
expression
\begintt
(V + V + V rotated 90 shifted 2right
  - V rotated-90 shifted 2up) rotated 90.
\endtt
[You must type this monstrous formula all on one line, even though it's too
long to fit on a single line in this book.]
\answer The pixel pattern is $\pixpat1121+\pixpat1121+\pixpat1112-\pixpat2111
=\pixpat1243$ before the final rotation, with the reference point at the
lower left corner of the~4; after rotation it is $\pixpat2314\,$, with the
reference point at the lower {\sl right\/} corner of the~4. Rotation causes
\MF\ to sort the edges, but the transition values per edge are never
more than $\pm3$. You weren't expected to know about this limit of $\pm3$,
but it accounts for what is actually reported:
\begintt
row 1: || -2++ -1+ 0---
row 0: || -2+ -1+++ 0--- 0-
\endtt

\ddanger If you ask for `|V| |rotated| |45|', \MF\ will complain that
$45↑\circ$ rotation is too hard. \ (Try it.) \ After all, square pixels
can't be ↑{rotated} unless the angle of rotation is a multiple of $90↑\circ$.
\MF\ also balks if you try `|V|~|scaled|~|2|'; this operation is meaningful,
but the author ↑↑{Knuth} was too lazy to implement anything for which he didn't
foresee any significant applications. On the other hand, `|V|~|scaled-1|'
does work; the result is
\begintt
>> Edge structure at line 5:
row -1: 0- -2+ 0- -1+ ||
row -2: 0- -2+ ||
\endtt

\ddangerexercise Why is `|V| |scaled-1|' different from `|-V|'\thinspace?
\answer `|V| |scaled-1|' should be the same as `|V| |rotated| |180|',
because transformations apply to coordinates rather than to pixel values.
\ (Note, incidentally, that the reflections `|V|~↑|xscaled-1|' and
`|V|~↑|yscaled-1|' both work, and that `|V|~|scaled-1|' is the same as
`|V|~|xscaled-1| |yscaled-1|'.)

\ddangerexercise Experiment with `|V| |shifted| |(1.5,3.14159)|' and
↑↑{shifted}  explain what happens.
\answer The result is the same as `|V| |shifted| |(2,3)|'; the coordinates
of a shift are rounded to the nearest integers when a picture is being shifted.

\ddangerexercise Why does the machine always speak of an ↑{edge structure}
`|at| |line|~|5|'\thinspace?
\answer \MF\ is currently executing instructions after having read
as far as line~5 of the file |expr.mf|.

\ddanger That completes our computer experiments. But before you log off,
you might want to try typing `|totalweight V/epsilon|', just to verify
that the sum of all pixel values in~$V$ is~5.

\ddanger The commands we have discussed so far in this chapter---@fill@,
@draw@, @filldraw@, @unfill@, etc.---are not really primitives of \MF;
they are macros of plain \MF, defined in Appendix~B. Let's look now
at the low-level operations on pictures that \MF\ actually performs
behind the scenes. Here is the syntax:
\beginsyntax
<picture command>\is<addto command>\alt<cull command>
<addto command>\is[addto]<picture variable>[also]<picture expressions>
 \alt[addto]<picture variable>[contour]<path expression><with list>
 \alt[addto]<picture variable>[doublepath]<path expression><with list>
<with list>\is<empty>\alt<with list><with clause>
<with clause>\is[withpen]<pen expression>%
 \alt[withweight]<numeric expression>\kern-3.5pt
<cull command>\is[cull]<picture variable><keep or drop><pair expression>
 \alt<cull command>[withweight]<numeric expression>
<keep or drop>\is[keeping]\alt[dropping]
\endsyntax
The \<picture variable> in these commands should contain a known picture;
the command modifies that picture, and assigns the resulting new value
to the variable.

\ddanger The first form of \<addto command>, `@addto@ $V$ @also@~$P$',
has essentially the same meaning as `$V:=V+P$'. But the @addto@ statement
is more efficient, because it destroys the old value of~$V$ as it adds~$P$;
this saves both time and space.  Earlier in this chapter we discussed
the ↑{reverse-video} ↑{dangerous bend}, which was said to have been
formed by the statement `$"currentpicture":="currentpicture"-"dbend"$'.
That was a little white lie; the actual command was
`@addto@ "currentpicture" @also@ $-"dbend"$'.

\ddanger The details of the other forms of `@addto@' are slightly more
complex, but (informally) they work like this, when $V="currentpicture"$
and $q="currentpen"$:
\begindisplay
Plain \MF&Corresponding \MF\ primitives\cr
\noalign{\smallskip}
↑@fill@ $c$&@addto@ $V$ @contour@ $c$\cr
↑@unfill@ $c$&@addto@ $V$ @contour@ $c$ @withweight@ $-1$\cr
↑@draw@ $p$&@addto@ $V$ @doublepath@ $p$ @withpen@ $q$\cr
↑@undraw@ $p$&@addto@ $V$ @doublepath@ $p$ @withpen@ $q$ @withweight@ $-1$\cr
↑@filldraw@ $c$&@addto@ $V$ @contour@ $c$ @withpen@ $q$\cr
↑@unfilldraw@ $c$&@addto@ $V$ @contour@ $c$ @withpen@ $q$ @withweight@ $-1$\cr
\enddisplay

\ddanger The second form of \<addto command> is `@addto@ $V$ @contour@ $p$',
followed by optional clauses that say either `@withpen@~$q$' or
`@withweight@~$w$'. In this case $p$~must be a cyclic path; each pen~$q$
must be known; and each weight~$w$ must be either $-3$,~$-2$, $-1$, $+1$,
$+2$, or~$+3$, when rounded to the nearest integer. If more than one pen or
weight is given, the last specification overrides all previous ones. If no
pen is given, the pen is assumed to be `"nullpen"'; if no weight is given,
the weight is assumed to be~$+1$. Thus the second form of \<addto command>
basically identifies a picture variable~$V$, a cyclic path~$p$, a pen~$q$,
and a weight~$w$; and it has the following meaning, assuming that
"turningcheck" is $\le0$: If~$q$~is the null pen, path~$p$ is digitized
and each pixel value is increased by $(j-k)w$, where $j$ and~$k$ are the
respective numbers of downward and upward path edges lying to the left
of the pixel (as explained earlier in this chapter). If $q$ is not the
null pen, the action is basically the same except that $p$ is converted to
another path that ``↑{envelope}s'' $p$ with respect to the shape of~$q$;
this modified path is digitized and filled as before. \ (The modified path
may cross itself in unusual ways, producing strange squirts of ink as
illustrated earlier. But it will be well behaved if path~$p$ defines a
↑{convex} region, i.e., if a car that drives around $p$ never turns toward
the right at any time.)

\ddanger If $"turningcheck">0$ when an `$@addto@\ldots@contour@$' command
↑↑"turningcheck" is being performed, the action is the same as just
described, provided that path~$p$ has a positive ↑{turning number}.
However, if $p$'s turning number is negative, the action depends on
whether or not pen~$q$ is simple or complex; a complex pen is one whose
boundary contains at least two points. If the turning number is negative
and the pen is simple, the weight~$w$ is changed to~$-w$. If the turning
number is negative and the pen is complex, you get an error message about
a ``↑{backwards path}.''  Finally, if the turning number is zero, you get
an error message about a ``↑{strange path},'' unless the pen is simple and
$"turningcheck"≤1$.  Plain \MF\ sets $"turningcheck":=2$; the ↑@filldraw@
macro in Appendix~B avoids the ``backwards path'' error by explicitly
reversing a path whose turning number is negative.

\ddanger The third form of \<addto command> is `@addto@ $V$ @doublepath@~$p$',
followed by optional clauses that define a pen~$q$ and a weight~$w$ as in
the second case. If $p$ is not a cyclic path, this case reduces to the
second case, with $p$ replaced by the doubled-up path
`$p\mathbin{\&}\mathop{\rm reverse}p \mathbin{\&}\cycle$' (unless $p$
consists of only a single point, when the new path is simply
`$p\to\cycle$'\thinspace). On the other hand if $p$ is a cyclic
path, this case reduces to {\sl two\/} addto commands of the second type,
in one of which $p$ is reversed; "turningcheck" is ignored during both of
those commands.

\ddanger An anomalous result may occur in `@addto@ $V$ @doublepath@ $p$' when
$p$~is a very small cyclic path and the pen $q$ is very large: Pixels
that would be covered by the pen regardless of where it is placed on~$p$
might retain their original value. If this unusual circumstance hits you,
the cure is simply to include the additional statement
`@addto@ $V$ @doublepath@~$z$', where $z$ is any point of~$p$, since this
will cover all of the potentially uncovered pixels.

\ddanger The ↑@cull@ command transforms a picture variable so that
all of its pixel values are either 0 or a specified weight~$w$, where $w$~is
determined as in an @addto@ command. A pair of numbers $(a,b)$ is given,
where $a$ must be less than or equal to~$b$. To cull ``@keeping@ $(a,b)$''
means that each new pixel value is $w$ if and only if the corresponding
old pixel value~$v$ was included in the range $a\le v\le b$; to cull
``@dropping@ $(a,b)$'' means that each new pixel value is $w$ if and only
if the corresponding old pixel value~$v$ was {\sl not\/} in that range.
Thus, for example, `↑@cullit@' is an abbreviation for
\begindisplay \advance\belowdisplayskip by -4pt
@cull@ "currentpicture" @keeping@ $(1,"infinity")$
\enddisplay
or for
\begindisplay \advance\abovedisplayskip by -4pt
@cull@ "currentpicture" @dropping@ $(-"infinity",0)$
\enddisplay
(which both mean the same thing). A more complicated example is
\begindisplay
@cull@ $V↓5$ @dropping@ $(-3,2)$ @withweight@ $-2$;
\enddisplay
this changes the pixel values of $V↓5$ to $-2$ if they were $-4$ or less,
or if they were 3 or~more; pixel values between $-3$ and $+2$, inclusive,
are zeroed.

\ddanger A cull command must not change pixel values from zero to nonzero.
For example, \MF\ doesn't let you say `@cull@ $V↓1$ @keeping@ $(0,0)$',
since that would give a value of~1 to infinitely many pixels.

\ddangerexercise What is the effect of the following sequence of commands?
\begindisplay
@picture@ $V[\,]$; \ $V↓1=V↓2="currentpicture"$;\cr
@cull@ $V↓1$ @dropping@ $(0,0)$; \
 @cull@ $V↓2$ @dropping@ $(-1,1)$;\cr
$"currentpicture":=V↓1-V↓2$;\cr
\enddisplay
\answer The pixel values of "currentpicture" become 1 if they were $\pm1$,
otherwise they become~0.

\ddangerexercise Given two picture variables $V↓1$ and $V↓2$, all of whose
pixel values are known to be either 0 or~1, explain how to replace $V↓1$ by
(a)~$V↓1\cap V↓2$; \ (b)~$V↓1\cup V↓2$; \ (c)~$V↓1\oplus V↓2$. \ [The
{\sl↑{intersection}\/} $V↓1\cap V↓2$ has 1's where $V↓1$ and $V↓2$ both are~1;
the {\sl↑{union}\/} $V↓1\cup V↓2$ has 0's where $V↓1$ and $V↓2$ both are~0;
the {\sl↑{symmetric difference}\/} or {\sl↑{selective complement}\/} ↑↑{xor}
$V↓1\oplus V↓2$ has 1's where $V↓1$ and $V↓2$ are unequal.]
\answer (a) @addto@ $V↓1$ @also@ $V↓2$; @cull@ $V↓1$
@keeping@ $(2,2)$. \ (b) Same, but cull keeping $(1,2)$.
\ (c)~Same, but cull keeping $(1,1)$.

\ddangerexercise Explain how to test whether or not two picture variables
are equal.
\answer Subtract one from the other, and cull the result dropping $(0,0)$;
then test if the total weight is zero.

\ddangerexercise Look at the definitions of @fill@, @draw@, etc., in
Appendix~B and determine the effect of the following statements:
\begindisplay
\llap{a) }@draw@ $p$ @withpen@ $q$;\cr
\llap{b) }@draw@ $p$ @withweight@ 3;\cr
\llap{c) }@undraw@ $p$ @withweight@ $w$;\cr
\llap{d) }@fill@ $c$ @withweight@ $-2$ @withpen@ $q$;\cr
\llap{e) }@erase@ @fill@ $c$ @withweight@ 2 @withpen@ "currentpen";\cr
\llap{f) }@cullit@ @withweight@ 2.\cr
\enddisplay
\answer (a)~Same as `@draw@ $p$', but using $q$ instead of the currently-picked-up
pen. \ (b)~Same effect as `@draw@~$p$; @draw@~$p$; @draw@~$p$' (but faster).
\ (c)~Same as `@draw@~$p$ @withweight@~$w$', because @undraw@'s
 `@withweight@~$-1$' is overridden.
\ (d)~Same as `@unfilldraw@~$c$; @unfilldraw@~$c$',
 but using $q$ instead of "currentpen".
\ (e)~Same as `@erase@ @filldraw@~$c$', because the `@withweight@~2' is
overridden. \kern-.7pt
\ (f)~Same effect as `@cullit@; @addto@ "currentpicture" @also@ "currentpicture"'
(but faster).
\ [Cases (a), (b), (d), and~(f) are useful; but---alas, alack!---cases (c)
and~(e) are counter-intuitive.]

\ddangerexercise Devise a ↑@safefill@ macro such that `@safefill@ $c$' increases
the pixel values of "currentpicture" by~1 in all pixels whose value would
be changed by the command `@fill@~$c$'. \ (Unlike @fill@, the @safefill@ command
never stops with a ``↑{strange path}'' error; furthermore, it never increases
a pixel value by more than~1, nor does it decrease any pixel values, even when the
cycle~$c$ is quite wild.)
\answer @def@ @safefill@ @expr@ $c$ $=$
	↑@begingroup@ ↑@save@ "region";\parbreak
@picture@ "region"; "region"="nullpicture";\parbreak
↑@interim@ $"turningcheck":=0$; \ @addto@ "region" @contour@ $c$;\parbreak
@cull@ "region" @dropping@ $(0,0)$;
	\ @addto@ "currentpicture" @also@ "region"\parbreak
↑@endgroup@ @enddef@.

\endchapter


A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject
\beginchapter Appendix A. Answers to\\All the\\Exercises

The preface to this manual points out the wisdom of trying to figure out
each exercise before you look up the answer here. But these answers are intended
to be read, since they occasionally provide additional information that
you are best equipped to understand when you have just worked on a problem.

\immediate\closeout\ans % this makes the answers file ready
\ninepoint
\input answers

\endchapter

Calle these foule Offendors to their Answeres.
\author WILLIAM ↑{SHAKESPEARE}, {\sl Second Henry the Sixth\/} (1600?) %
	% fixthis [2 Hen VI, II.i.203]

\bigskip

If you can't solve a problem,
you can always look up the answer.
But please, try first to solve it by yourself;
then you'll learn more and you'll learn faster.
\author DONALD E. ↑{KNUTH}, {\sl The %
 {\manual \char`\\]\char`\↑\char`\_efg\char`\↑}\kern1ptbook\/} (1985)

\eject
\beginchapter Appendix J. Joining the\\\TeX\ Community

This appendix is about grouping of another kind: \TeX\ and \MF\ users from
around the world have banded together to form the \TeX\ Users Group (TUG),
in order to exchange information about common problems and solutions.

A semiannual newsletter called {\sl TUGboat\/} has been published
since 1980, featuring articles about all aspects of \TeX\ and \MF. ↑↑{TeX}
TUG has a network of ``site coordinators'' who serve as focal points of
communication for people with the same computer configurations.
Occasional short courses are given in order
to provide concentrated training in special topics; videotapes of
these courses are available for rental.
Meetings of the entire TUG membership are held at least once a year.
You can buy \MF\ T-shirts at these meetings.

Information about membership in TUG and subscription to {\sl TUGboat\/}
is available from

\smallskip
{\obeylines
\TeX\ Users Group
c/o American Mathematical Society
P.O. Box 9506
Providence RI 02940-9506, USA.
}

\endchapter

TUG is established to serve members having a common interest
in \TeX, a system for typesetting technical text,
and in\/ \MF\!, a system for font design.
\author T\kern-.15em\lower.5ex\hbox{E}\kern-.005em X %
 USERS GROUP, {\sl Bylaws, Article II\/} (1983) % TUGboat 4 (1983) p60

\bigskip

Don't delay, write today! That number again is
\TeX\ Users Group
c/o American Mathematical Society
P.O. Box 9506
Providence RI 02940-9506, USA.
\author DONALD E. ↑{KNUTH}, {\sl The \TeX book\/} (1985) % Appendix J

\eject
\end  But Don, be sure to see MANMAC page 6 before you publish this!
\beginchapter Chapter X. A Chapter\\Template

Start the text here.

\endchapter

A first quotation.
\author A FIRST ↑{AUTHOR},  {\sl A First Source\/} (18xx)

\bigskip

A second quotation.
\author A SECOND ↑{AUTHOR},  {\sl A Second Source\/} (19xx)

\eject